How to combine vectors based on value?
5 ビュー (過去 30 日間)
古いコメントを表示
Good Afternoon,
Another quick question. Say I have a matrix,
B = [732145 732151 732168 0 0 0 0
284 281 297 0 0 0 0]
and
C =
[ 0 281 284 0 0 297 0
0 0 0 0 0 0 0]
I am trying to get it so that I have:
D = [0 281 284 0 0 297 0
0 732151 732145 0 0 732168 0].
Should I be using the [r c] kind of terminology. I keep almost getting there, I think, then I get confused.
Any thoughts would be greatly appreciated! or reading!
Thank you very much for any time!
0 件のコメント
回答 (3 件)
Guillaume
2015 年 10 月 16 日
Regarding your latest comment, a much simpler way of obtaining your D result, assumming that elements of B and C are uniques is:
assert(numel(unique(C)) == numel(C) && numel(unique(B)) == numel(B)); %does not work if elements are not unique
[values, ic, ib] = intersect(C, B);
D = zeros(numel(C), numel(B));
D(sub2ind(size(D), ic, ib)) = values;
If the values of B and C are not unique, you need an additional level of indirection through unique.
Andrei Bobrov
2015 年 10 月 16 日
B = [4 5 6 7; 0 0 0 0; 0 0 0 0; 0 0 0 0];
C = [0; 5; 4];
D = B;
[ll,idx] = ismember(B(1,:),C);
D(sub2ind(size(D),1+idx(ll),find(ll))) = C(idx(ll));
0 件のコメント
Geoff Hayes
2015 年 10 月 14 日
Do you wish to simply iterate over each element in the first row of C and, for those that are non-zero, check to see if it exists in the second row of matrix B and copy the the value from its first row into D? If so, try the following
D = C;
for k=1:size(C,2)
if C(1,k) ~= 0
[idx] = find(B(2,:)==C(1,k));
if ~isempty(idx)
D(2,k) = B(1,idx);
end
end
end
In the above, we just iterate over each column in the first row of C. If the element is non-zero then we use find to find that element of the second row of B that matches the value in C. If the returned index, idx, is non-empty then we set this value to the corresponding element of D.
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!