Rezvan
Rezvan

Reputation: 1

fast code instead of for loop with if

I was wondering if you see a fast way in MATLAB to convert the following "for" loop into a one-line calculation that is more efficient.

A=[2;4;0;6;1;0];
B=[1;3;0;4;0;5];
C=[2,4,8,5,7;
11,44,2,8,9;
43,2,1,87,3;
13,26,7,9,3;
12,2,6,3,23;
18,42,6,7,2];
for i=1:size(A,1)
 D(i,1)=i-1;
if (A(i,1)~=0)
    if (B(i,1)==0)
        D(i,2)=0;
    else
            D(i,2)=C(A(i,1),B(i,1));
    end
else
                D(i,2)=0;
end
end

Upvotes: 0

Views: 41

Answers (1)

BillBokeey
BillBokeey

Reputation: 3476

Well, you can use sub2ind :

D=zeros(numel(A),2);

D(:,1)=0:(numel(A)-1);

LinearIds=sub2ind(size(C),A(A~=0&B~=0),B(A~=0&B~=0));

D(A~=0&B~=0,2)=C(LinearIds);

Output :

D =

    0   11
    1    7
    2    0
    3    7
    4    0
    5    0

Upvotes: 2

Related Questions