How to vectorize assignment from array of structures to cell array

1 回表示 (過去 30 日間)
Jon
Jon 2019 年 8 月 6 日
コメント済み: Jon 2019 年 8 月 6 日
I am looking for a way to make an assignment from an array of structures to a cell array without using a loop.
Here is an example of what I am doing using a loop
% make up a very simple array of structures
s(1).pet = 'cat'
s(2).pet = 'fish'
s(3).pet = 'dog'
% would like to have a cell array listing the pets
% equivalent to the result of C1 = {'cat','fish','dog'}
% can get this using a loop
C1 = cell(1,3); % preallocate
for k = 1:3
C1{k} = s(k).pet;
end
I unsuccessfully attempted to do without a loop
C2 = {s.pet};
But C2 is not the same as C1. It is a cell array with three elements each of which is a 1x1 cell array
So to summarize, my question. In the above example code how can I assign s(1).pet, s(2).pet and s(3).pet to a cell array C to give the result C = {'cat','fish','dog'} without using a loop?
p.s. If my usage of the term "array of structures" here is not correct please let me know.

採用された回答

madhan ravi
madhan ravi 2019 年 8 月 6 日
C = {s.pet} % is giving you the desired result already
  2 件のコメント
madhan ravi
madhan ravi 2019 年 8 月 6 日
If you want to check if they are the same simply:
isequal(C1,C)
Jon
Jon 2019 年 8 月 6 日
Yes you are right they are the same. So I guess my second method works after all. Apparently when I was doing this earlier I had made some other mistake with my test case and had incorrectly concluded that this didn't work. I should have tested the example I put up here.
Sorry for the confusing post.
Thanks for your help

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

その他の回答 (0 件)

カテゴリ

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

タグ

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by