user3541731
user3541731

Reputation: 1

Substitute elements of a matrix at specific coordinates in matlab

I am struggling to write code to substitute particular values in a matrix.

I have a matrix, C, that contains multiple [r,c,v] values. I now want to use these co-ordinates to substitute values from matrix X with those from matrix Y- but only at the coordinates in matrix c. At the coordinates not in matrix c I would like to retain the values from matrix X.

As a simple example of what I am trying to do:

o1= [ 123 123 123; 123 255 123; 255 123 123];
o2= [ 4 4 4; 4 4 4; 4 4 4];
d1= [111 111 111; 111 255 111; 111 111 111];
d2= [5 5 5; 5 5 5; 5 5 5];

o_p= o1;
d_p= d1;

need to find coordinates in o_p and d_p where the values equal 255

[r,c,v] = find(o_p==255);
a= [r, c, v];

[r,c,v] = find(d_p==255);
b= [r, c, v];

c= [a; b];

Then I want to use the coordinates in c to replace the elements at these coordinates in both matrices with o2 and d2 respectively

Upvotes: 0

Views: 145

Answers (2)

Divakar
Divakar

Reputation: 221704

Do you mean 255 to be present in both [o_p and d_p] or [o_p or d_p]?

If and try this -

ind1 = find((o_p==255) & (d_p==255))

If or try this -

ind1 = find((o_p==255) | (d_p==255))

and then do -

o2(ind1)=d2(ind1)

Hope this is what you are after!

Upvotes: 0

sco1
sco1

Reputation: 12214

The question isn't entirely clear, but I'm going to make some assumptions and hopefully the solution is close to what you're looking for.

% Example

x = rand(12,12);
y = ones(12,12);
% Assume c = [x,y]
c = [1 1; 2 2; 3 3; 4 4];  % Pick a few arbitrary points on the diagonal
x(sub2ind(size(x),c(:,1),c(:,2))) = y(sub2ind(size(x),c(:,1),c(:,2)))

In order to do this in one line you can take advantage of how MATLAB stores values in memory. Because MATLAB technically stores matrix in a single column, you can access any value in the matrix with a 1D index instead of nD coordinates. sub2ind allows you to obtain these indices based on the input coordinates and size of the matrix, which you can then use to swap values between matrices.

Upvotes: 1

Related Questions