ciklee
ciklee

Reputation: 55

changing certain elements in a 2D array

I'm working on an algorithm in Matlab that requires certain elements of a matrix to be updated regularly and looking how best to do this. Here is a description of what i'm trying to achieve:

  1. I have a MxN array A and 1xN vector B.
  2. Basically, vector B is a logical index that describes which column of A that I need to select i.e. C = A(:,B).
  3. Unfortunately, logical vector B varies depending on some processes. This means the number of columns in C is not fixed.
  4. Some other processing will use C as inputs and produce another array D that has the same size as C i.e. size(D) == size(C)
  5. Now, I need to "reshape" D so that it has the same size as A. The tricky part is those columns in A that weren't chosen in #2 above needs to be replaced by NaNs. Of course I can do it the crude way of using loops. But I'm looking to do this the Matlab-way i.e. linear or logical indexing, vectorization, etc This is where I got stuck at the moment.

Some examples to make things clearer:

Lets say

A = [1 2 3; 4 5 6; 7 8 9] 
B = [1 0 1] 
C = A(:,B) = [1 3; 4 6; 7 9] 

After some processing, I'll get D = [2 5; 6 7; 3 3]. Now, I need to "reshape" D into the same size as A by padding with NaN i.e. D = [2 NaN 5; 6 NaN 7; 3 NaN 3].

What I've tried so far,

Atmp = NaN(size(A));
Btmp = find(repmat(B,[size(B,1),1]));
Atmp(Btmp) = D(Btmp); %-> error because D is smaller than A.

Upvotes: 0

Views: 326

Answers (1)

Shai
Shai

Reputation: 114976

How about

fullD = NaN(size(A));
fullD(:, B) = D;

Upvotes: 2

Related Questions