Writing data to a structure array without loop

% Let an array of axes be given
ax(1)=axes;
ax(2)=axes;
ax(3)=axes;
% Let's write something to axes user data in the "data" field
ax(1).UserData.data=1;
ax(2).UserData.data=1;
ax(3).UserData.data=1;
% Now change "data" in all axes to "2"
for i=1:numel(ax)
ax(i).UserData.data=2;
end
How can this be done without a loop?
I could write somethng like this:
s.data=2;
[ax.UserData] = deal(s);
But if there were another user data in these axes (e.g. ax(1).UserData.data1='something';), they will be gone. I need to change only one field, without affecting the other fields.

3 件のコメント

Stephen23
Stephen23 2019 年 7 月 5 日
編集済み: Stephen23 2019 年 7 月 5 日
"How can this be done without a loop?"
There is no easy way to do this without a loop. A loop is the easiest way to access the data of nested non-scalar structures. Why do you need to avoid using a loop?
madhan ravi
madhan ravi 2019 年 7 月 5 日
Stephen +1
bbb_bbb
bbb_bbb 2019 年 7 月 5 日
Thank you for the answer.
I always wonder how some operations can be done without a loop. This time I killed half a day for this, and decided to ask the community.

サインインしてコメントする。

 採用された回答

Jan
Jan 2019 年 7 月 5 日

0 投票

As written by Stephen before:
There is no vectorized way to set the value of sub-fields of struct arrays.
The expression
[ax(1:3).UserData.data] = ...
cannot work, because [ax(1:3).UserData] creates a comma separated list, but you cannot obtain a subfield of such a list by the dot operator.
A loop is a simple and efficient solution. If you have spent a half day for searching a vectorized version, you are a victim of the "premature optimization" programming pattern. In many cases the programming and debug time exceeds the run time massively, such that the total time to solve a problem does not profit from too tricky improvements in lines of code, which do not consume a remarkably part of the total processing time. So start with writing dull loops and if the program is running and tested successfully, use the profiler to find the most time consuming parts. Optimize these bottlenecks only.

その他の回答 (1 件)

KSSV
KSSV 2019 年 7 月 5 日

0 投票

6 件のコメント

bbb_bbb
bbb_bbb 2019 年 7 月 5 日
編集済み: bbb_bbb 2019 年 7 月 5 日
This does not work...
T = num2cell(2);
[ax(1:3).UserData.data] = T;
"A partial reference returned 3 results instead of exactly 1."
KSSV
KSSV 2019 年 7 月 5 日
Why?
bbb_bbb
bbb_bbb 2019 年 7 月 5 日
And why should it work?
KSSV
KSSV 2019 年 7 月 5 日
T = num2cell(1:2);
ax = struct('UserData',T)
bbb_bbb
bbb_bbb 2019 年 7 月 5 日
This gives
ax(1).UserData
ans =
1
But it should be:
ax(1).UserData
ans =
data: 2
KSSV
KSSV 2019 年 7 月 5 日
Yes......UserData.Data is must?

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2019 年 7 月 5 日

回答済み:

Jan
2019 年 7 月 5 日

Community Treasure Hunt

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

Start Hunting!

Translated by