简体   繁体   中英

Changing elements of two matrix in a condition matlab

Consider two n by n-1 matrix and an n by 1 vector (for example lets call them in order A, B and v). Elements of v are zero or one. If element v(m,1) is equal to one, I want to replace elements A(1:m-1,m-1) by B(1:m-1,m-1) and elements A(m+1:n,m) by B(m+1:n,m). How can I do that? Could anyone help? To make the question more clear, consider below example.

example:

A=[1,2,3;4,5,6;7,8,9;12,13,14]
B=[3,4,5;6,7,8;9,10,11;6,5,3]
v=[0,1,0,1]

Result should be:

result= [3,2,5;4,5,8;7,10,11;12,5,14]

You can acheive the desired result using find , which returns the indexes on non-zero elements, and a for -loop:

R = A; % assuming you've set A, B and v already.
n = size(A,1);
v1 = find(v);
for i=1:length(v1)
     m=v1(i);
     if m>1
     R(1:m-1,m-1)=B(1:m-1,m-1);
     end
     if m<n
         R(m+1:end,m)=B(m+1:end,m);
     end
end

As I point out in a comment, v has to have length n-1 if v(n-1)=1 otherwise m+1:end is not a valid index range.

Edited to make second assignment optionally as per comments.

Here is an alternative, using logical indexing:

temp = A;
ind = 1:size(v,2);
for k = ind(v==1)
    if k<=size(A,2)+1
        A(1:k-1,k-1) = B(1:k-1,k-1);
        B(1:k-1,k-1) = temp(1:k-1,k-1);
        if k<size(A,2)
            A(k+1:end,k) = B(k+1:end,k);
            B(k+1:end,k) = temp(k+1:end,k);
        end
    end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM