سؤال

I would like to index a part of a matrix using a logical mask. So as an input I have a Matrix A where there are some nan values, I create a mask for this using isnan. Moreover I have a vector v of values that I would like to insert into A A(mask)=v. Then I construct another matrix B using A B=[A;A;A]. Now I would like to apply the values in v to the right position in B. How can I do it in Matlab without creating temp=B(1:size(A,1),1:size(A,2)) matrix or to create a new mask=[mask;false(2*size(A,1),size(A,2))]?

One more time:

A = rand(2,10);
v = A(A>0.5);
A(A>0.5) = nan;
mask = isnan(A);
B=[A;A;A];

% now how to write v to B?
% not doing one of those: 

tmp = B(1:2,:);
tmp(mask) = v;
B(1:2,:) = tmp;

%...

mask1 = [mask;false(4,10)]

mask2 = [false(2,10);mask;false(2,10)]

mask3 = [false(4,10);mask]

B(mask1) = v;
B(mask2) = v;
B(mask3) = v;

% what i miss is something like B(1:2,:)(mask) 
هل كانت مفيدة؟

المحلول

I assume you want to fill values at each of the three occurrences of A within B.

If you don't mind repeating the vector v:

B = repmat(A.',1,3); % easier to work by columns
B(bsxfun(@plus,find(mask.'),(0:2)*numel(A))) = v(repmat(1:numel(v),1,3)); % fill
B = B.'; % transpose back

نصائح أخرى

Not sure if I understand your wording correctly, but if you put these lines at the end:

mask2 = repmat(mask, 3, 1);
B(mask2) = NaN

It will repeat the NaN values 3 times vertically. It depends on what you mean by 'apply the values in v to the right position in B'

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top