Coming soon - Get a detailed view of why an account is flagged as spam!
view details
2
Logical indexing with structure arrays
Post Flair (click to view more posts with a particular flair)
Post Body

Using logical indexing with structs is always a headache for me. I've come to a wall where I'm not sure if there is an "elegant" way to do a one-liner to get the desired result. Say I have a structure array A with many fields, one of which is, say, a1. This field is always an array of doubles but the arrays are of various lengths. So for example we may have

A(1).a1=[1 2 3]  
A(2).a1=[1 2 3 4 5]  
A(3).a1=[1 2]  
A(4).a1=[1 2 3 4 5 6 7]  

Suppose I would like to create a new structure that consists of all the rows of A where a1 is longer than 3, which in this case would be the equivalent of

B=[A([3 4])]  

This seemed a little helpful but I'm unable to finagle working syntax to work the length function into a logical index.

I can immediately conceive of some for loop structures that would get me what I want. I could do something like

lengthlist=zeros(1,length(A));
for i=1:length(A)
    lengthlist(i)=length(A(i).a1);
end

And then I imagine

B=[A(lengthlist>3)]  

would give me what I want. I just want to know if there is a "smarter" way using fewer lines (and avoiding a for loop) to do this. My "real" array has a length of 87 which will not crush me for using for loops but I'm still trying to learn best practices for Matlab.

Author
Account Strength
100%
Account Age
16 years
Verified Email
Yes
Verified Flair
No
Total Karma
88,096
Link Karma
12,527
Comment Karma
75,272
Profile updated: 5 days ago
Posts updated: 9 months ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
9 years ago