Backspace
Backspace

Reputation: 23

Appending a row/column of different size to an array.

Recently, I came across this behaviour in Matlab and I am curious as to know why this happens.

a(1,:) = rand(4,1);
a(2,:) = rand(5,1);

This throws me Subscripted assignment dimension mismatch. error whereas

a(1,:) = rand(4,1);
a(2,1:5) = rand(5,1);

adjusts the array to the max column size and appends zero to the shorter ones.

My question is: Why the former code snippet doesn't do what the latter does(which seems very logical to me)? I don't see any reason as to why the former code snippet should work the way it does. Or am I missing something?

Upvotes: 0

Views: 54

Answers (1)

Brice
Brice

Reputation: 1580

With a(2,:) = rand(5,1);, you are attempting to assign a 5x1 vector to a 4x1 matrix column. Hence the error.

With a(2,1:5) = rand(5,1);, you are explicitly referencing a 5th row, which tells the Matlab engine to expand the matrix accordingly before attempting the assignment operation. Hence, this will succeed.

The way I see it, trying to put 5 values into a 4 row vector likely comes from an error in the code, so the user has to explicitly state that this is what he intends to do. Of course, I can only infer on the intent of Mathworks developers when they specifiy the behavior of their language.

Upvotes: 2

Related Questions