简体   繁体   中英

Unable to perform assignment because the left and right sides have a different number of elements

I have an array StartMeasuring, which is filled with 10 numbers. I would like to fill the matrix Depth with 10 arrays counting down to zero from the numbers in StartMeasuring.

StartMeasuring=randi([10 30],1,10);
lenDepth =len(StartMeasuring);
Depth=NaN(lenDepth,30);

for i=1:lenDepth
    Depth(i)=StartMeasuring(i):-1:0;
end

I tried to create a for loop and replacing a matrix with NaN 's, but I get the error :

Unable to perform assignment because the left and right sides have a different number of elements.

Error in sd (line 53)
    Depth(i)=StartMeasuring(i):-1:0;

I don't understand why I get this error since both Depth and StartMeasuring are size 10.

StartMeasuring=randi([10 30],1,10);
lenDepth = length(StartMeasuring); % numel is preferred
Depth = NaN(lenDepth,31);

for ii = 1:lenDepth
    Depth(ii,1:StartMeasuring(ii)+1) = StartMeasuring(ii):-1:0;
end

Indexing with a singular number, like you did initially, gets, unsurprisingly, a single element of the matrix. Instead, index into the row as a single number, letting it fill all columns based on the expression. Read more about indexing in this great post .

Also the size of StartMeasuring(ii):-1:0 is random between 30 and 1, meaning that you have to store it based on its current length, which in your case (integers) is given by StartMeasuring(ii)+1 .

Figure showing imagesc(Depth) :

在此处输入图片说明


Note that I changed several other things:

  • len is Python, not MATLAB. Use length , or, preferably for 1D arrays numel
  • spaces around the assignment operator = make for better readability
  • i and j are the imaginary unit and it's customary to not use them as variable names in MATLAB.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM