For loop not working on logical indexing

4 views (last 30 days)
Kirby Runyon
Kirby Runyon on 13 Mar 2017
Edited: Adam on 13 Mar 2017
I have a vector and a matrix. The vector is distance (22 elements long) and the logical matrix is LandingVelocities_index (22x548) which finds the max velocity in MeanVelocityPerBox (also 22x548). I'm trying to find the speed of particles that correspond to a distance based on their row (1 thru 22). Doing this manually works, but doing it in a for loop gives me an error (Subscripted assignment dimension mismatch.)
Manually, this works
LandingVelocityDistance(1,4)=distance(find(LandingVelocities_index(:,4)==1))
where the "4" could be any column 1-548.
In this loop, it does not work:
LandingVelocityDistance=ones(1,length(MeanVelocityPerBox)); %Pre-allocate space
for h=1:length(MeanVelocityPerBox)
LandingVelocityDistance(1,h)=distance(find(LandingVelocities_index(:,h)==1));
end
Ultimately, I want to end up with two vectors of the same length that allow me to plot max velocity versus distance. Any tips appreciated.

Answers (1)

Adam
Adam on 13 Mar 2017
I suspect there are quicker ways than a for loop, but just focussing on your code, I suspect in some cases 'find' is returning multiple results.
doc find
mentions a second argument to the function which you should use (and you ought to have find underlined in that code with a message if you hover over it telling you this).
find( LandingVelocities_index(:,h)==1, 1 )
will return only the first element it finds matching the criteria. Of course if it isn't only the first you want then that is a different matter and your code would have to be able to handle that on the left side of your assignment (e.g. using a cell array to accommodate variable length answers)
  2 Comments
Kirby Runyon
Kirby Runyon on 13 Mar 2017
Thanks, but I'm afraid this doesn't work. The answer will be a vector (distance), so I shouldn't need a cell array. That will correspond to the vector of velocities from the vector MaxLandingVelocities (which is where the logical index came from)
Adam
Adam on 13 Mar 2017
Edited: Adam on 13 Mar 2017
Well, find is either returning too many results or none to be getting a subscripted assignment dimension mismatch error.
Using the debugger and the 'Stop on Errors' option from the breakpoints menu in the editor will make it trivial to understand what is going wrong. Or
dbstop if error

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!