Info

この質問は閉じられています。 編集または回答するには再度開いてください。

Seperating a vector based on another vector

1 回表示 (過去 30 日間)
Luffy
Luffy 2015 年 11 月 6 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
I have two arrays A & B.vector A has to be separated & processed based on B's vector value.For the length that B's value remains same,A has to be taken till that value & processed.
Example:-
A = 1:10;
B = [5 5 5 5 5 10 10 10 10 10];
%so B's first 5 values are same.so A's first 5 values should be assigned to a different array on which i'll do processing.
%Again B's next 5 values are same,so A's next 5 values are to be assigned to that another array on which i can process.
%My approach:-
C = unique(B);
for i = 1:length(C)
for j = 1:length(A)
if A(j) == unique(i)
D(j) = A(j)
else
D(j) = [ ]
end
end
% do processing on D
end
Can this be done in any better way ?
  2 件のコメント
Guillaume
Guillaume 2015 年 11 月 6 日
編集済み: Guillaume 2015 年 11 月 6 日
I assume the line
if A(j) == unique(i)
is meant to read
if B(j) == C(i)
Otherwise the code makes no sense.
Luffy
Luffy 2015 年 11 月 6 日
yes,that's right

回答 (1 件)

Guillaume
Guillaume 2015 年 11 月 6 日
編集済み: Guillaume 2015 年 11 月 6 日
For a start your inner j loop is completely unnecessary, use logical vector indexing:
C = unique(B);
for idx = 1:numel(C) %avoid using i, it's a matlab function
D{idx} = A(B == C(idx)); %B == C(idx) is a logical vector, used to index A
end
Another way of achieving the same result is to use accumarray:
[~, ~, locations] = unique(B);
D = accumarray(locations, A, [], @(v) {v});
D = arrayfun(@(c) A(B == c), unique(B), 'UniformOutput', false);

この質問は閉じられています。

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by