Matrix manipulation and replacements

2 views (last 30 days)
I have a large matrix A (size 116x116) and a small matrix B (64x64)...
in B i only have all 2s or 5s ... In A i have 2s 3s etc..
I know the vector of rows and collumns that match matrix B..ie Irow 1by64 and Jcol 1by64;
I want to replace A(Irow,Jcol) with matrix elements in B; but only if the parent matrix A location is not equal to 2..
I.e. if A already has a 5 it should not be replace.
If I do A(Irow, Jcol) = B; then some of the 5s I have in A are getting replaced by 2s in B which I do not want.
Please help.
here is a smaller e.g. for illustration
A =[2 2 3 1
5 5 5 5
2 2 2 2
2 3 5 5];
B = [2 5
5 5];
Need to rplace A(Irow,Jcol) where Irow is a vector of size 2 and Jcol is vector of size 2) however, it can be arbitrary and located anywhere within the domain of A.

Accepted Answer

Niels
Niels on 20 Jan 2017
there is an easy solution if the matrices have the same size, so you coule just crewate a new matrix C which is A(Irow,Jcol)
A =
2 2 2 2
5 5 5 5
2 2 2 2
2 2 5 5
>> B=[inf nan; nan inf] % replaced 3 and 4s by nan and inf, so that you can see the replacements
B =
Inf NaN
NaN Inf
>> [Irow,Jcol]=size(B);
>> C=A(1:Irow,1:Jcol)
C =
2 2
5 5
% now check where C (which is A(...) ) is not equal to 2 and replace with matching index of matrix B
>> C(C~=2)=B(C~=2)
C =
2 2
NaN Inf
>> A(1:2,1:2)=C
A =
2 2 2 2
NaN Inf 5 5
2 2 2 2
2 2 5 5
  1 Comment
Pappu Murthy
Pappu Murthy on 20 Jan 2017
This solution is very nice and cute and compact. I accept it as the most direct answer. Thanks for the help.

Sign in to comment.

More Answers (1)

Wilson A N
Wilson A N on 20 Jan 2017
I think you can use the 'sub2ind' command as shown in the code below:
A = rand(3,3)
A =
0.8059 0.8305 0.1025
0.0777 0.6046 0.6690
0.0537 0.4764 0.0370
A(sub2ind([3 3],[1,2],[2,3]))= [2, 5]
A =
0.8059 2.0000 0.1025
0.0777 0.6046 5.0000
0.0537 0.4764 0.0370
Here I replaced the locations A(1,2) and A(2,3) with 2 and 5 respectively. More information on sub2ind command can be found in the link given below:

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!