フィルターのクリア

how to add element to a cell array struct without loop

1 回表示 (過去 30 日間)
Xiaodi
Xiaodi 2017 年 8 月 20 日
コメント済み: Xiaodi 2017 年 8 月 20 日
Hi, I have a cell array, each of them is a structure, I want to add values in all arrays with field name myfield, how I do it without a loop?
for i = 1:10
C{i}.myfield = 1;
end
I can not use
C{1:10}.myfield = 1;
because it has the error:Expected one output from a curly brace or dot indexing expression, but there were 10 results. Maybe is there another simple method?
Thanks forward

採用された回答

Stephen23
Stephen23 2017 年 8 月 20 日
編集済み: Stephen23 2017 年 8 月 20 日
This would be trivially easy if you had stored your data in a non-scalar structure (instead of inefficiently in lots of separate structures in a cell array):
>> [S(1:10).data] = deal(1)
S =
1x10 struct array with fields:
data
>> S(1).data
ans =
1
>> S(6).data
ans =
1
  3 件のコメント
Stephen23
Stephen23 2017 年 8 月 20 日
編集済み: Stephen23 2017 年 8 月 20 日
Unless there is a good reason why you need to keep the structures separate (e.g. different sizes or fields) I would simply convert to a non-scalar structure first, which would make all of your processing and code much simpler and more efficient. All you need is:
S = cell2mat(C)
You do not need to make your code ugly and inefficient because of someone else's bad data design.
PS: there is no way to access the structures in a cell array like that without a loop.
Xiaodi
Xiaodi 2017 年 8 月 20 日
Thanks a lot!!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by