mat2str 到元胞数组的泛化 [英] Generalization of mat2str to cell arrays

查看:32
本文介绍了mat2str 到元胞数组的泛化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有时会错过一个函数来生成(可能是嵌套的)元胞数组的字符串表示.这将是 mat2str 的概括,它仅适用于非- 元胞数组(数值型、字符型或逻辑型).

I sometimes miss a function to produce a string representation of a (possibly nested) cell array. It would be a generalization of mat2str, which only works for non-cell arrays (of numeric, char or logical type).

给定一个数组x,如何得到一个字符串表示y,使得对这个字符串求值得到x?

Given an array x, how to obtain a string representation y, such that evaluating this string produces x?

例如输入

x = {[10 20], {'abc'; false; true;}};

应该产生一个像

y = '{[10 20], {''abc''; false; true}}';

(或有关分隔分隔符的一些变体),使得

(or some variation regarding spacing an separators), such that

isequal(x, eval(y))

true.

推荐答案

这个过程,将一个数据结构转换成一个可以被评估的字符串,被命名为 序列化.

This process, transforming a data structure into a string that later can be evaled, is named serialization.

有一个 Octave 的序列化函数 可用于此目的,它支持任何核心数据类型(不仅是元胞数组)具有任意数量的维度(不仅仅是 2d).

There is a serialize function for Octave that can be used for this purpose which supports any core data type (not only cell arrays) with any number of dimensions (not only 2d).

示例:

## Works for normal 2d numeric arrays
octave> a = magic (4);
octave> serialize (a)
ans = double([16 2 3 13;5 11 10 8;9 7 6 12;4 14 15 1])
octave> assert (eval (serialize (a)), a)

## Works for normal 3d numeric arrays with all precision
octave> a = rand (3, 3, 3);
octave> serialize (a)
ans = cat(3,double([0.53837757395682650507 0.41720691649633284692 0.66860079620859769189;0.018390655109800025518 0.56538265981533797344 0.20709955358395887304;0.86811365238275806089 0.18398187533949311723 0.20280927116918162634]),double([0.40869259684132724919 0.96877003954154328191 0.32138458265911834522;0.37357584261201565168 0.69925333907961184643 0.10937000120952171389;0.3804633375950405294 0.32942660641033155722 0.79302478034566603604]),double([0.44879474273802461015 0.78659287316710135851 0.49078191654039543534;0.66470978375890155121 0.87740365914996953922 0.77817214018098579409;0.51361398808500036139 0.75508941052835898411 0.70283088935085502591]))
octave> assert (eval (serialize (a)), a)

## Works for 3 dimensional cell arrays of strings
octave> a = reshape ({'foo', 'bar' 'qux', 'lol', 'baz', 'hello', 'there', 'octave'}, [2 2 2])
a = {2x2x2 Cell Array}
octave> serialize (a)
ans = cat(3,{["foo"],["qux"];["bar"],["lol"]},{["baz"],["there"];["hello"],["octave"]})
octave> assert (eval (serialize (a)), a)

然而,更好的问题是您首先为什么要这样做?如果您这样做的原因是在 Octave 的多个实例之间发送变量,请考虑使用 parallelmpi 包,其中包含专门为此目的设计的功能.

However, a better question is why do you want to do this in the first place? If the reason you're doing this is to send variables between multiple instances of Octave, consider using the parallel and mpi packages which have functions specialized designed for this purpose.

这篇关于mat2str 到元胞数组的泛化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆