2
votes

Assume we have a matrix A (2x5), with the first row containing the numbers:

1 2 3 5 7

and the second row:

0.4 0.1 0.2 0.1 0.2

Also, there is a 10 dimensional vector B with numbers 1,2,3...10. How can I create a new 10 dimensional vector C that will only contain the values of A (second row) when A(1,:) == B, else 0.

So the new vector C should have the form:

0.4 0.1 0.2 0 0.1 0 0.2 0 0 0 

(add zero for the cells of B that are not in A).

I tried this solution but I have a problem due to the difference in dimensions between A and B.

for i=1:53
    if B(i) == A(1,i)
        C{1,i} = A(2,i);
    else
        C{1,i}=0;
    end
end 

Index exceeds matrix dimensions.

3

3 Answers

2
votes

It's not very clear what you're after, but this at least gives the desired output:

A = [1 2 3 5 7; 0.4 0.1 0.2 0.1 0.2];
B = 1:10;
[tf,loc] = ismember(A(1,:), B);
C = zeros(1,10);
C(loc(tf)) = A(2,tf)

[I'm assuming you mean 10 element vector, rather than 10 dimensional...]

If you just want to use the first row of A as indices and the second row as assigned values, then you don't need to use B at all and you can do something like this:

A = [1 2 3 5 7; 0.4 0.1 0.2 0.1 0.2];
C = zeros(1,10);
C(A(1,:)) = A(2,:)
2
votes

How about removing the for loop and do it inline using ismember function:

A = [1 2 3 5 7; 0.4 0.1 0.2 0.1 0.2];
B = 1:10;
C = zeros(1,10);
C(B(ismember(B, A(1,:)))) = A(2,ismember(A(1,:),B));

Hint: Even if we happen to have a value in A(1,:) which B does not have, this solution will work.

0
votes

Using ismember and a for loop:

clc; clear;

A=[
    1 2 3 5 7;
    0.4 0.1 0.2 0.1 0.2
  ];

B = 1:10;

C = zeros(1,10);
for j = 1:10
    if ismember(j, A(1,:))
            C(j) = A(2, A(1,:) == j);
    else
        C(j) = 0;
    end
end
C