How to remove items from two arrays that index each other without for loop

1 回表示 (過去 30 日間)
Al in St. Louis
Al in St. Louis 2018 年 10 月 23 日
コメント済み: Al in St. Louis 2018 年 10 月 23 日
This is hard to explain in words. Here's my code, and I'd like to know whether there's a way to vectorize the part with a for loop:
t = [obj.network.node(obj.posIx).type];
mPosIx = obj.posIx (t == 13 | t == 9);
mIxPos = zeros (1, max (mPosIx));
for idx = 1:length(mPosIx)
mIxPos (mPosIx (idx)) = idx;
end
This code does exactly what I need it to do. It removes all items that aren't type 9 or 13. The mPosIx array points to the correct position in the node array. The mIxPos array either contains a zero where there is no corresponding element in the position array (which does not appear in this code), or it contains the correct index in the position array. The for loop just feels clunky, but I couldn't figure out another way to do it.
  4 件のコメント
madhan ravi
madhan ravi 2018 年 10 月 23 日
what do you mean by this?
mIxPos (mPosIx (idx)) = idx;
Al in St. Louis
Al in St. Louis 2018 年 10 月 23 日
It's a line of code that assigns the index of the for loop, idx, to the correct position. Here's the output of running the code on my test data. I get two vectors with the correct values in the correct positions. I just want to get rid of the for loop.
>> mIxPos
mIxPos =
1 0 0 0 2
>> mPosIx
mPosIx =
1 5

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

採用された回答

Bruno Luong
Bruno Luong 2018 年 10 月 23 日
You can vectorize LHS as with RHS, the for loop becomes one line
mIxPos(mPosIx) = 1:length(mPosIx);
That returns the inverse of permutation mPosIx
  1 件のコメント
Al in St. Louis
Al in St. Louis 2018 年 10 月 23 日
That's much better than calling find and saving two of its three outputs. My function has been reduced to:
t = [obj.network.node(obj.posIx).type];
mPosIx = obj.posIx (t == 13 | t == 9);
mIxPos (mPosIx) = 1:numel (mPosIx);

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

その他の回答 (1 件)

Al in St. Louis
Al in St. Louis 2018 年 10 月 23 日
This works:
mIxPos = zeros (1, max (mPosIx));
[~,col,v]=find(mPosIx)
mIxPos (v) = col;

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by