creating structures in nested for loop
8 ビュー (過去 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!