Reputation: 2030
I have the following matrix in MATLAB where the first column contains just ones:
How can I replace the values in column 1 (regardless of what the original value is) with a new value (e.g. 99) within a specific index range (e.g. just for rows 9 to 12) to obtain this:
If I use the following command I can replace all the 1 in the first column with 99:
finalMatrix(finalMatrix(:,1) == 1,1) = 99;
To replace just the values in column 1 from index 9 to 12 I tried this
finalMatrix(finalMatrix(9:12,1) == 1,1) = 99;
but it doesn't work.
Any suggestion?
Upvotes: 0
Views: 1755
Reputation: 46445
When you do
finalMatrix(finalMatrix(9:12,1) == 1,1) = 99;
you will actually replace the first 4 elements of finalMatrix
, assuming that the corresponding values in 9:12
were ==1
. The reason is that Matlab does the following steps:
1) generate a 4x1 matrix finalMatrix(9:12,1)
2) figure out which of the four elements is ==1
3) return a boolean array (four elements long) corresponding to those elements
4) perform logical indexing on finalMatrix with these four elements -
which now reference the first four elements of the first column of finalMatrix
You just need
finalMatrix(9:12,1) = 99;
Or, if you care that the values were 1 to begin with, you could do
indx = find(finalMatrix(9:12,1)==1);
finalMatrix(indx+8,1)=1;
Upvotes: 3