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!