Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexing into vector

Tags:

matlab

Can someone please explain why in example A the result is 1x6 vector (which makes sense and was what I was expecting) whereas in example B the result is 1x4 vector?

In example B if I predefine the size of newvec to be a 1x6 vector then the result is the correct 1x6 vector. Just not understanding what is going on.

Example A

vec = [0 2 3 0 5 0]     %1x6
newvec(vec == 0) = 1    %produces a 1 x 6 vector

Example B

vec = [0 2 3 0 5 3]     %1 x 6
newvec(vec == 0) = 1    %produces a 1 x 4 vector
like image 397
mHelpMe Avatar asked Jun 13 '14 10:06

mHelpMe


1 Answers

If newvec doesn't exist when you call the second line, MATLAB only makes it as large as it needs to hold the indexes you're setting to 1.

What you're actually doing is:

newvec([1 4 6]) = 1; or

newvec([1 4]) = 1;

Similarly if vec was actually a 2D/3D etc. matrix, newvec will come out as 1 x N, where N is whatever the highest index number is, and not retain the shape of the original matrix.

So, in these cases you need to either:

1) preallocate newvec to be the size of vec first.

2) Do newvec = (vec==0) instead

like image 144
nkjt Avatar answered Oct 14 '22 23:10

nkjt