creating structures in nested for loop
12 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Guillaume
il 7 Lug 2016
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 Commenti
Guillaume
il 7 Lug 2016
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).
Più risposte (1)
Thorsten
il 7 Lug 2016
Modificato: Thorsten
il 7 Lug 2016
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 Commenti
Guillaume
il 7 Lug 2016
For matrices, Subscript indices must either be real positive integers or logical is an absolute rule in matlab.
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!