Matlab 中的动态赋值
我有一个 cellarray ,其值用于初始化相应的结构。
cellarr = {'NI' ; 'EQ' ; 'TA' } ;
defstr = struct('Raw', '-1') ;
for i = 1:size(cellarr,1)
eval([cellarr{i,1} '= defstr;']) %Yes,I know eval is bad!Any other approach?
end
然后将新值填充到 Raw
字段中。
dataCell = [] ;
for i=1:size(cellarr,1)
rawCell = [cellarr{i} '.Raw'] ;
dataCell = strcat(dataCell, ', ', rawCell) ;
end
dataCell(1) = [] ;
DESIRED STATEMENT NOW --> [NI.Raw,Eq.Raw,TA.Raw] = filldata()
function[a1,a2,a3] = filldata(), a1 = 1 ; a2 = 2 ; a3 = 3 ; end
即使使用eval
,我也无法执行所需的语句
。将感谢您的帮助。 filldata
输出计数将与所需语句
的 LHS 输出计数相匹配。谢谢。
I have a cellarray
whose values are used to initialize corresponding structs.
cellarr = {'NI' ; 'EQ' ; 'TA' } ;
defstr = struct('Raw', '-1') ;
for i = 1:size(cellarr,1)
eval([cellarr{i,1} '= defstr;']) %Yes,I know eval is bad!Any other approach?
end
New values are then filled into the Raw
field.
dataCell = [] ;
for i=1:size(cellarr,1)
rawCell = [cellarr{i} '.Raw'] ;
dataCell = strcat(dataCell, ', ', rawCell) ;
end
dataCell(1) = [] ;
DESIRED STATEMENT NOW --> [NI.Raw,Eq.Raw,TA.Raw] = filldata()
function[a1,a2,a3] = filldata(), a1 = 1 ; a2 = 2 ; a3 = 3 ; end
I am not able to execute the desired statement
, even by using eval
. Shall appreciate your help. filldata
output count would match that of LHS of desired statement
. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是 EVAL 的一个可能的解决方案:
与任何其他解释语言一样,使用 EVAL 不是最佳实践(但您似乎已经知道这一点)。
除非您特别需要其名称只能在运行时确定的变量,否则我将使用元胞数组或结构数组(取决于您的需要):
Here is a possible solution for EVAL:
As in any other interpreted language, the use of EVAL is not best practice (but you seem to already know that).
Unless you specifically need to have variables whose names can only be determined at runtime, I would use cell-arrays or array of structures instead (depending on your needs):