Assigning Multiple Vectors in a Structure Field

I need to assign multiple vectors as the value of a field in a structure. How do I go about doing this? When I try this
for j = 1:2
for i = 1:3
basis(j).a(i) = [1 0 0];
end
end
I get this error: "Subscripted assignment dimension mismatch."
The following works, but I can't use cell arrays.
for j = 1:2
for i = 1:3
basis(j).a{i} = [1 0 0];
end
end

回答 (3 件)

Walter Roberson
Walter Roberson 2018 年 1 月 31 日

1 投票

The fact that a structure is involved is not relevant. You are trying to do the equivalent of
for i = 1:3
a(i) = [1 0 0];
end
which attempts to store a numeric vector of length 3 into a location that expects only one numeric value.
If you need to store multiple values in a location, then you need to use cell arrays, or you need to use some kind of object-oriented object that can store a vector as a property... which is pretty much the same thing as trying to use a cell array.
Matt J
Matt J 2018 年 1 月 31 日
編集済み: Matt J 2018 年 1 月 31 日

0 投票

Maybe as follows,
for j = 1:2
for i = 1:3
basis(j).a(i,1:3) = [1 0 0];
end
end
Jos (10584)
Jos (10584) 2018 年 1 月 31 日

0 投票

I think you're looking for this:
for j=1:2
b(j).a = [1 0 0] ; % assign vector to field
end
which can be easier accomplished using deal:
[b2(1:2).a] = deal([1 0 0])

カテゴリ

ヘルプ センター および File ExchangeStructures についてさらに検索

質問済み:

2018 年 1 月 31 日

回答済み:

2018 年 1 月 31 日

Community Treasure Hunt

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

Start Hunting!

Translated by