Index exceeds array bounds, when call a function with struct parameter

조회 수: 1 (최근 30일)
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

채택된 답변

Stephen23
Stephen23 2019년 9월 10일
편집: Stephen23 2019년 9월 10일
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개)

카테고리

Help CenterFile Exchange에서 Functional Programming에 대해 자세히 알아보기

태그

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by