How to add two columns based on conditions

4 ビュー (過去 30 日間)
Eric
Eric 2025 年 9 月 10 日
コメント済み: Star Strider 2025 年 9 月 10 日
I was going to try to write a very basic loop (to familiarize myself with writing loops), otherwise not using a loop would probably cost less.
I have a large matrix, but for simplicity, I am trying to add 2 columns together and create the sum in another column in the same matrix.
I want to have two conditions to be met in order for the addition to take place, if conditions are not met, then do not combine values, but still generate the first value.
So I want to add column 3 and 4, if column 1 x<1.5 and if column 2 x==0, then insert into column 5. If the critieria is not met, then copy value from column 3 into 5.
1 0 1 4 5
2 0 1 5 1
1 1.5 2 1 2
if intrun(:,1)<1.50) & (intrun(:,2)==0;
intrun(:,5)= intrun(:,3)+intrun(:,4);
end
Thank You

採用された回答

Star Strider
Star Strider 2025 年 9 月 10 日
It is easiest to use 'logical indexing' for this.
Try this --
intrun = [1 0 1 4; 2 0 1 5; 1 1.5 2 1]
intrun = 3×4
1.0000 0 1.0000 4.0000 2.0000 0 1.0000 5.0000 1.0000 1.5000 2.0000 1.0000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Lv = intrun(:,1)<1.50 & intrun(:,2)==0
Lv = 3×1 logical array
1 0 0
intrun(Lv,5) = intrun(Lv,3) + intrun(Lv,4)
intrun = 3×5
1.0000 0 1.0000 4.0000 5.0000 2.0000 0 1.0000 5.0000 0 1.0000 1.5000 2.0000 1.0000 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
intrun(~Lv,5) = intrun(~Lv,3)
intrun = 3×5
1.0000 0 1.0000 4.0000 5.0000 2.0000 0 1.0000 5.0000 1.0000 1.0000 1.5000 2.0000 1.0000 2.0000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
.
  2 件のコメント
Eric
Eric 2025 年 9 月 10 日
Thank you!
Star Strider
Star Strider 2025 年 9 月 10 日
As always, my pleasure!

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

その他の回答 (0 件)

カテゴリ

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

タグ

製品


リリース

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by