Remove for-loop by using cellfun
1 次查看(过去 30 天)
显示 更早的评论
var_name = {'A','B','C'};
for i=1:length(var_name)
eval([cell2mat(var_names(i)) '=zeros(10,1);'])
end
How can I do?
Thanks in advance
3 个评论
Cedric
2014-7-3
编辑:Cedric
2014-7-3
If all "variables" contents are 10x1 numeric arrays, it would be much more natural/efficient (and simpler) to build an array of zeros. For 3 "variables", for example:
nData = 3 ;
data = zeros( 10, nData ) ;
and then use e.g.
data(:,2) = ...
to get the column vector for the second data.
采纳的回答
James Tursa
2014-7-3
编辑:James Tursa
2014-7-3
You can't avoid the for loop. Either it will be explicitly in your code, or whatever MATLAB function you use will have it in the background. It isn't a big deal in your case, so I would just advise keeping it explicit. Makes your code more readable anyway. E.g.,
z = zeros(10,1);
for i=1:length(var_name)
eval([var_names{i} '=z;'])
end
The reason for doing the "z = zeros(10,1)" up front is to create shared data copies of the 10x1 zeros matrix instead of individual ones. For you small example (106 variables) it won't make any practical difference in timing, but I thought I would include this option just for completeness of the example.
0 个评论
更多回答(3 个)
Robert Cumming
2014-7-3
Create the dynamic variables inside a struct instead of using eval
var_name = {'A','B','C'};
for i=1:length(var_name)
myStruct.(var_name{i}) = zeros(10,1);
end
the cyclist
2014-7-3
编辑:John D'Errico
2014-7-3
Please tell us you are not naming those 106 variables A,B,C, ..., AA, AB, AC, etc!
Could you do this via a cell array instead?
for n = 1:106
A{n} = zeros(10,1);
end
and use those as your variables?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!