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.
Post Details
- Posted
- 9 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/matlab/comm...