How does numel work in adding zeroes to change the dimension of a vector in matlab?

Viewed 37

I am trying to add two vectors; however, they do not have the same dimensions. For example only (since the one I am doing have 1000+ values), the vectors are:

a = [1 2 3 4 5];
b = [1 2];

Since they do not have the same dimensions, I want to simply add zeroes to vector b to match the dimension of vector a.

Using the code b(numel(a)) = 0; I was able to do it. However, I am quite confused on how it worked as I only saw this code on the internet. I know that numel(a) is equal to 5, but I don't know how that code was able to add zeroes after 1 2 in variable b to match the dimension of variable a.

Can anyone explain?

1 Answers

When you set b(5) = 0, matlab can not simply leave the intervening elements b(3:4) unfilled, so they get zeros. If you did b(numel(a)) = 1, the intervening elements would still be filled with zero.

Keep in mind that this is a short cut that only works if you know for that fact that b is shorter than a. If not, you will be setting an element of b to 0, which is likely not what you want.

Related