Remove for-loop by using cellfun

조회 수: 1 (최근 30일)
Christophe
Christophe 2014년 7월 3일
편집: James Tursa 2014년 7월 3일
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
Christophe
Christophe 2014년 7월 3일
The objective is to make preallocation for about 106 variable (which are double).
Cedric
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
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.

추가 답변 (3개)

Robert Cumming
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
  댓글 수: 1
Christophe
Christophe 2014년 7월 3일
The objective is not to use struct.
Thanks for you answer

댓글을 달려면 로그인하십시오.


the cyclist
the cyclist 2014년 7월 3일
I suggest you read this document for some suggestions.

the cyclist
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?
  댓글 수: 2
Christophe
Christophe 2014년 7월 3일
I'm not naming these variables A, B, C ... Variables names have already been defined by another user. These varaibles names are linked to another software (AMESIM from Siemens/LMS) & here is few examples: injector_delay, mass_fuel ... I want to use vectorization to avoid for-loop & I think we can use cell2fun but I don't know how to
John D'Errico
John D'Errico 2014년 7월 3일
Changed zeros{10,1} to zeros(10,1).

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by