Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace values in matrix with other values

Tags:

matrix

matlab

I have a matrix with integers and I need to replace all appearances of 2 with -5. What is the most efficient way to do it? I made it the way below, but I am sure there is more elegant way.

a=[1,2,3;1,3,5;2,2,2]
ind_plain = find(a == 2)
[row_indx col_indx] = ind2sub(size(a), ind_plain)
for el_id=1:length(row_indx)
    a(row_indx(el_id),col_indx(el_id)) = -5;
end

Instead of loop I I seek for something like: a(row_indx,col_indx) = -5, which does not work.

like image 500
user1597969 Avatar asked Aug 14 '12 12:08

user1597969


People also ask

How do you substitute values in a matrix?

You can specify the value to replace as c , M(1,3) or M(3,1) . To replace a particular element of a matrix with a new value while keeping all other elements unchanged, use the assignment operation. For example, M(1,1) = 2 replaces only the first element of the matrix M with the value 2.

How do you change a value in an array in Matlab?

B = changem( A , new ) replaces all occurrences of 0 in array A with the specified scalar new . This function is useful for replacing values in classification grids. B = changem( A , new , old ) replaces all occurrences of old with new .

How do you replace in Matlab?

To replace text in the file, click the expand button to the left of the search field to open the replace options. Then, enter the text that you want to replace the search text with and use the Replace and Replace all buttons to replace the text.


3 Answers

find is not needed in this case. Use logical indexing instead:

a(a == 2) = -5

In case of searching whether a matrix is equal to inf you should use

a(isinf(a)) = -5

The general case is:

Mat(boolMask) = val

where Mat is your matrix, boolMask is another matrix of logical values, and val is the assignment value

like image 179
Andrey Rubshtein Avatar answered Oct 18 '22 18:10

Andrey Rubshtein


Try this:

a(a==2) = -5;

The somewhat longer version would be

ind_plain = find(a == 2);
a(ind_plain) = -5;

In other words, you can index a matrix directly using linear indexes, no need to convert them using ind2sub -- very useful! But as demonstrated above, you can get even shorter if you index the matrix using a boolean matrix.

By the way, you should put semicolons after your statements if (as is usually the case) you're not interested in getting the result of the statement dumped out to the console.

like image 13
Martin B Avatar answered Oct 18 '22 17:10

Martin B


The Martin B's method is good if you are changing values in vector. However, to use it in matrix you need to get linear indices.

The easiest solution I found is to use changem function. Very easy to use:

mapout = changem(Z,newcode,oldcode) In your case: newA = changem(a, 5, -2)

More info: http://www.mathworks.com/help/map/ref/changem.html

like image 1
Palli Avatar answered Oct 18 '22 18:10

Palli