How to save a value from an array if a condition is true

28 ビュー (過去 30 日間)
Tejashree Pawar
Tejashree Pawar 2021 年 10 月 21 日
コメント済み: Geoff Hayes 2021 年 10 月 25 日
I have two cell arrays "X" and "Y". I need to check if a value in X==1, then save the corresponding Y value. How to do that in a for loop (I have many runs of X and Y)

回答 (1 件)

Geoff Hayes
Geoff Hayes 2021 年 10 月 21 日
@Tejashree Pawar - do you need to use a loop? For example, if your X and Y arrays are the same dimensions, then (for example) if
X = [1 2 3 1 4 5 1 6 7];
Y = [7 2 2 8 2 2 9 2 2];
Z = Y(X==1)
then Z is
Z =
7 8 9
since X==1 returns a logical array of ones and zeros where a one corresponds to the match (to 1) in X. We can then use this logical array to extract those values from Y which match the logical 1.
  2 件のコメント
Tejashree Pawar
Tejashree Pawar 2021 年 10 月 21 日
Hi @Geoff Hayes thanks for the answer! Yes, i need to use it in a for loop because i have multiple X and Y files (CANape test data). X&Y are of same dimension for a given run.
How would i make it work if X and Y were cell arrays?
Geoff Hayes
Geoff Hayes 2021 年 10 月 25 日
@Tejashree Pawar - couldn't you just use a single for loop to iterate over each element of X and then compare to 1? If true, then extract the equivalent element from Y and insert into an array. Is the problem keeping track of the data from each run?

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by