creating structures in nested for loop
11 次查看(过去 30 天)
显示 更早的评论
I want to create a struct inside a nested for loop i am getting error, can someone explain or guide me a---> Integer b---> double c----> double value
for a=1:5
for b=0:0.1:1
%x=num2cell(b);
field1='hey'; value1=a;
field2='bey'; value2=num2cell(b);
field3='cey'; value3=num2cell(c);
%ish=zeros(50,5);
ish(a,b)=struct(field1,(value1),field2,(value2),field3,(value3));
end
end
I tried to reallocate memory before running still i do not get the desired result
Error is : Subscript indices must either be real positive integers or logical s.
0 个评论
采纳的回答
Guillaume
2016-7-7
The problem has nothing to do with structures. You're using an non-integer b as a subscript into a matrix (of structures in this case but the same would be true with a matrix of number). This is not allowed in matlab. As the error message says: "Subscript indices must either be real positive integers or logical"
Note that if all you want to is create a structure a numel(a) x numel(b) structure with a, b, and the scalar c, then:
a = 1:5;
b = 0:0.1:1;
c = pi; %or whatever value you want
[aa, bb, cc] = ndgrid(a, b, c);
ish = struct('hey', num2cell(aa), 'bey', num2cell(bb), 'cey', num2cell(c))
Note that in your original code, since you're putting scalars into each field, the conversion to cell with num2cell is completely unnecessary.
4 个评论
Guillaume
2016-7-7
You can create a table from a structure, a cell array, a matrix or directly and fill it up in a loop.
I've no idea what you're trying to do anymore as this seems completely unrelated to your original example. Note that tables are not really practical for 3D data as in your example (2D matrix + fields).
更多回答(1 个)
Thorsten
2016-7-7
编辑:Thorsten
2016-7-7
You use b as index into a matrix
ish(a,b)
with b=0:0.1:1. This does not work, indices have to be 1, 2, 3,... or logical, i.e. false or true (logical 0 or logical 1).
One way to do it:
% fields can be defined outside loop when they are always the same
field1='hey';
field2='bey';
field3='cry';
b = 0:0.1:1;
c = 23; % you forgot to define c
for a = 1:5
for i = 1:numel(b) % generate index into b
ist(a, i) = struct(field1,a,field2,b(i),field3,c);
end
end
2 个评论
Guillaume
2016-7-7
For matrices, Subscript indices must either be real positive integers or logical is an absolute rule in matlab.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!