フィルターのクリア

Matrix padding with logical index

3 ビュー (過去 30 日間)
Piment
Piment 2014 年 7 月 6 日
回答済み: Roger Stafford 2014 年 7 月 6 日
I have a matrix(6 by 3) of different row lengths:
0.9969 0.9724 0.3951
0.3590 0.5865 0.3983
0.6252 0.7780 0.7513
NaN 0.7277 0.5224
NaN NaN 0.4904
NaN NaN 0.0887
and a logical index matrix that has same or longer row length(7 by 3) like:
1 0 1
1 1 1
0 1 0
0 0 1
0 1 1
0 1 1
1 0 1
how can I get the following results(7 by 3) without loop:
0.9969 0 0.3951
0.3590 0.9724 0.3983
0 0.5865 0
0 0 0.7513
0 0.7780 0.5224
0 0.7277 0.4904
0.6252 0 0.0887
Thanks very much in advance

採用された回答

Cedric
Cedric 2014 年 7 月 6 日
編集済み: Cedric 2014 年 7 月 6 日
Assuming that the first array is A, the logical array is B, and you want to build C:
C = zeros( size( B )) ;
C(find( B )) = A(~isnan( A )) ;
EDIT : if, for any reason, you needed the row index in A of elements of C, you could get them as follows
>> cumsum( B ) .* B
ans =
1 0 1
2 1 2
0 2 0
0 0 3
0 3 4
0 4 5
3 0 6
  1 件のコメント
Piment
Piment 2014 年 7 月 6 日
thank you very much Cedric!

サインインしてコメントする。

その他の回答 (1 件)

Roger Stafford
Roger Stafford 2014 年 7 月 6 日
In case it is of interest to you, the following code does not depend on placing NaNs in the first array. It uses the 1's in the second array to determine where to place elements from the first array as they are taken out in sequential order in each column. The only requirement is that for each column there be enough rows in the first array to match the number of 1's in that column of the second array. I call the first array x, the second one y, and the result z.
[r1,c] = find(y ~= 0);
f = find([diff(c)~=0])+1;
r2 = ones(size(c,1),1);
r2(f) = r2(f)-diff([1;f]);
r2 = cumsum(r2);
z = zeros(size(y));
z(r1+size(z,1)*(c-1)) = x(r2+size(x,1)*(c-1));

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by