How can I create a structure from a cell array of strings and give it the initial value of zero?
조회 수: 1 (최근 30일)
이전 댓글 표시
given:
a={
'S.f1' 'double' [1, 600] ;
'S.f2' 'uint8' [5,5];
'S.f3.ff1' 'int16' [5,2,10];
'S.f3.ff2' 'double' [1,60] }
I would like to have in my workspace contain a structure "S" having fields f1, f2, and f3, and I want f3 to have fields ff1 and ff2.
I do not want to explicitly type out :
S.f1 = zeros(1,600,'double');
S.f2 = zeros(5,5,'uint8');
S.f3.ff1 = zeros(5,2,10,'int16');
S.f3.ff2 = zeros(1,6,'double');
I am stumped by the fact that MATLAB does not recognize 'S' as a structure when I try to parse the assignment statements from 'a'.
x = cellfun (@zeros, a{:,3},a{:,2},'UniformOutput',false);
S=cell2struct(x,a{:,1},1);
does not work, nor does
evalin ('base',strcat(a{1,1}, '= ',x{1}));
please help.
댓글 수: 0
답변 (2개)
Image Analyst
2015년 4월 19일
No. How is it supposed to know you want to use zeros() just from the cell array? Maybe you might want ones() or rand(). There's nothing in the cell array to specify that - all it has is the numbers and classes and structure variable names/fields. I think that whoever created that cell array in the first place is not doing what most of us would do. Because of that you're going to have to parse each cell array row and use the hated eval() to "poof" your variables into existence. To see why we don't like doing this, see the FAQ: http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F then go back to the author who wrote the code that created your cell array and tell them to use a better way, which is maybe to just create the structure array at that time (when the cell array is being created) and save it out to a .mat file.
댓글 수: 0
per isakson
2015년 4월 19일
편집: per isakson
2015년 4월 19일
Your goal is that to create a nested structure with hundreds of fields?
x = cellfun(@zeros, a(:,3),a(:,2),'uni',false);
S = cell2struct( x, {'f1','f2','f3','f4'}, 1 )
S =
f1: [1x600 double]
f2: [5x5 uint8]
f3: [5x2x10 int16]
f4: [1x60 double]
I cannot see that the first column of a could be used without some parsing.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!