Extracting Non-Zero Values From Array and Applying to a Different Matrix

2 ビュー (過去 30 日間)
Samrita Dhindsa
Samrita Dhindsa 2018 年 7 月 10 日
編集済み: Matt J 2018 年 7 月 10 日
I have two 1 x n arrays, call them p = [p_1,..., p_n] and phi = [phi_1,...,phi_n]. It is possible that p will have zero values, and I would like to extract the nonzero values into a separate array, call it workingP. At the same time, for each nonzero value p_k, I would like to include phi_k in a second new array, workingPhi.
So ultimately, I will end up with workingP = {[p_k] : p_k ~= 0} and workingPhi = {[phi_k] : p_k ~= 0} where k ranges from 1 to n.
I'm not sure how to go about this without reallocating memory over and over again.

採用された回答

Guillaume
Guillaume 2018 年 7 月 10 日
tokeep = p ~= 0; %logical array indicating which elements to keep
workingP = p(tokeep);
workingPhi = phi(tokeep);

その他の回答 (1 件)

Matt J
Matt J 2018 年 7 月 10 日
編集済み: Matt J 2018 年 7 月 10 日
[~,idx,workingP] = find(p);
workingPhi = phi(idx);

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by