Stuart’s MATLAB Videos

Watch and Learn

This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

MATLAB: In an assignment A(I) = B, the number of elements in B and I must be the same. 8

Posted by Doug Hull,

The very common MATLAB error: “In an assignment A(I) = B, the number of elements in B and I must be the same.” occurs when one side of an assignment has a dfferent dimension than the other. So for instance the left side of the assignment might be a vector and the target on the left is a scalar. The problem might be that both sides are vectors, but one is a different length than the other. In this video Doug shows two ways to debug this common situation.

8 CommentsOldest to Newest

Kate replied on : 1 of 8
Thank you. I just want to express my deep appreciation to this video. This is very helpful to me in identifying the real problem behind the error report. The 'dbstop if error' command is powerful. Thank you again. Cheers.
Tobi replied on : 2 of 8
This error message would be waaaaaaaay more helpful if it gave a line number, just like any other error message does! Tobi
Stuart McGarrity replied on : 3 of 8
Hi Tobi, When are you not seeing a line number in the error? If you are selecting and evaluating some lines of code or you are using the "run section" feature you will not get a line number. Otherwise you should.
vijay replied on : 4 of 8
Ok, generally, nobody makes this exact error. The general error would be more like: newfinal(i) = final + a(i-1); Something like this blows up and it doesn't make any sense. In my case: inputfile(i) = [path file(i)]; gives me this error. I am trying to place each entry of fetched file (from uigetfile) into an array of inputfile. Why does this generate an error?
Stuart McGarrity replied on : 5 of 8
Hi Vijay, The error Doug describes is caused by a variable changing dimensions during the running of the code. Your line, newfinal(i) = final + a(i-1), on its own could not cause this type of error. Are you still getting an error? Have you tried dbstop on error and looking at the variables?
Stuart McGarrity replied on : 7 of 8
Hi Tahseen, You need to look at the dimensions of A(I) and B to make sure they are the same. Stop in the debugger it you need to.
Bhakti Kaushal replied on : 8 of 8
Very helpful video.. I am trying to run something like this in a for loop and getting the same error in second iteration, understood my mistake and I can now solve.. Thanks :)

Add A Comment

Your email address will not be published. Required fields are marked *

Preview: hide