Index exceeds array bounds, when call a function with struct parameter
1 view (last 30 days)
Show older comments
Hello every one,
Im trying to use Nested parfor and for-Loops, something like:
parfor n=1:2
s= struct();
s.x= [];
s.y= [];
s.z=[];
data=0;
for ii=1:5
for jj=1:10
[data,s(n)]= fun(data,s(n));
end
end
end
I couldn't solve the error of struct. where I can use s.x = fun(data,s(n)); on the other hand s(n)= fun(data,s(n)) is wrong syntax in parfor and I want to process all s fields.
it works when I use for loop, thanks in advance
0 Comments
Accepted Answer
Stephen23
on 10 Sep 2019
Edited: Stephen23
on 10 Sep 2019
A structure is an array. It can be empty, or scalar, or have size 2x3, or whatever size you want, just like any otther type of array (e.g. numeric, char, cell, etc.).
In your code you created a scalar structure:
>> s = struct(); % this creates a scalar structure with no fields
>> size(s)
ans =
1 1
>> isscalar(s)
ans =
1
Therefore it makes absolutely no sense to try to index into its 2nd element, ... because that element simply does not exist. You did not create element s(2), so trying to index into s(2) will fail.
"...I want to process all s fields."
It seems that you are confusing the size of a structure with how many fields a structure has. These are two totally independent things: the size of a structure makes absolutely no difference to how many fields it has. The number of its fields is totally independent from its size.
If you want to iterate over the fields of a structure, then you need to iterate over the fields of that structure, e.g.:
fld = fieldnames(s);
for k = 1:numel(fld)
s.(fld{k})
end
0 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!