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.

采纳的回答

Guillaume
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 个评论
Yash
Yash 2016-7-7
Is it possible to create a table using structure of array?? Or is it better to create a table inside nested for loop using http://nl.mathworks.com/help/matlab/ref/table.html
Guillaume
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
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 个评论
Yash
Yash 2016-7-7
Is there any method to use b in ish(a,b) ?
Guillaume
Guillaume 2016-7-7
For matrices, Subscript indices must either be real positive integers or logical is an absolute rule in matlab.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by