MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today**New to MATLAB?**

Asked by Peter
on 15 Jan 2012

a=[]; b=[]; for i=1:length(l) [m n]=find(R==l(i)); a(i)=m; b(i)=n; end In an assignment A(I) = B, the number of elements in B and I must be the same.

In this code l is a column vector and R a matrix containing all elements of l and more.This 'for loop' is contained in yet another 'for loop'.Now for the first couple loops in the bigger 'for loop' no error is given.Then halfway through, the error shown above is displayed. I cannot understand why this happens, and why the error is not given all the time.

*No products are associated with this question.*

Answer by the cyclist
on 15 Jan 2012

Accepted answer

What is likely happening is that at first, your find() command is finding exactly one instance of R==l(i), and therefore there is one value of [m,n]. But if there are multiple instances of R==l(i), then there is a vector of [m,n] values, and that cannot be assigned to a(i) and b(i), which are scalar elements.

You should be able to breakpoint into your code and see for which value of i this is happening.

Answer by Image Analyst
on 15 Jan 2012

That's NOT going to give you what you think it will. Your index will ALWAYS be either empty or just one. You're getting the error when it's empty (no match). It's not going to give you a list of indexes where l matches R. Even if you do put in a check for empty, your a and b will just be 1 or 0, not the indices.

Simply say

[a b] = find(R == l);

and do away with the for loop altogether, and get the indices like you want.

Or if you really want a binary comparison (match or no match), simply do

binaryMap = l == R;

Answer by Peter
on 15 Jan 2012

10x a lot for your help.I knew that R should contain exactly once the the number I was searching for.But it turns out due to some bugs in my program R was being overwritten so [m n] was returning empty. Many thanks!

Image Analyst
on 15 Jan 2012

Exactly what I said. I wrote up a little demo and tested it and that's how I discovered the "empty" problem before I answered. I'm not sure how you used cyclists answer to resolve your problem or why you still chose to do it that way instead of the "isempty()" way or "loopless/vectorized" way I suggested, but anyway, for small loops it shouldn't matter much.

## 0 Comments