How to extract only certain values from a field in a structure array?

Hello, I am trying to output only certain values from a field in a structure array called Cells. The values I want are in the pos field, and I only want the value when the values in the Type field are equal to 1, and thus when P is 1. This is my code so far. It works in the command window and gives me all the variables, when I do not assign Cells(P).pos to a variable. But my problem is that when I assign Cells(P).pos to a variable it only gives me one value, versus for all the values P is true. How do I get all the values and still assign them to a variable? I tried to preallocate prof as an empty matrix but that didn't work either. Thanks!
P=[Cells.Type]==1;
Prof= Cells(P).pos;

 採用された回答

Ahmet Cecen
Ahmet Cecen 2016 年 5 月 8 日
編集済み: Ahmet Cecen 2016 年 5 月 8 日

0 投票

I am not aware of a way to do this without a for loop. If you run:
P=[Cells.Type]==1
without the semi colon, you will see every element in the array correctly outputs the type check, yet they are not being captured as an array. The following should work:
for i = 1:length(Cells)
if Cells(i).Type == 1
Prof(i) = Cells(i).pos;
end
end

3 件のコメント

Rasha  Bara
Rasha Bara 2016 年 5 月 8 日
Thanks! That gave me the values I need! However, is there a way I can output only the values in Prof that are not zeros? I tried writing this, but that gave me an array of logicals versus only the actual values of Prof that are not zero.
P= Prof~=0;
Ahmet Cecen
Ahmet Cecen 2016 年 5 月 8 日
ii = 0;
for i = 1:length(Cells)
if Cells(i).Type == 1
ii = ii + 1;
Prof(ii) = Cells(i).pos;
end
end
OR following your idea, deleting the zero entries after the fact:
for i = 1:length(Cells)
if Cells(i).Type == 1
Prof(i) = Cells(i).pos;
end
end
Prof (Prof==0) = [];
Rasha  Bara
Rasha Bara 2016 年 5 月 8 日
Thanks! That worked perfectly!

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

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2016 年 5 月 8 日

3 投票

P=[Cells.Type]==1;
Prof= vertcat(Cells(P).pos);

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by