MATLAB: Change specific col and row in a matrix

change value of matrix in specific location

Hi, let say i have matrix A=[20 40 60 70; 10 20 30 40; 60 50 20 10]. I want to change value in these location (e.g (2,2),(3,2),(1,4)) to 5 without having typing one by one to change the value.. how i can do that?

Best Answer

A=[20 40 60 70; 10 20 30 40; 60 50 20 10] ;
r = [2 3 1] ;
c = [2 2 1] ;
B = A ;
% Method 1 , use loop
for i = 1:length(r)
A(r(i),c(i)) = 5 ;
end
% Method 2, use indices
idx = sub2ind(size(A),r,c) ;
B(idx) = 5 ;