If Else simple calculation not working

1 ビュー (過去 30 日間)
Jorge Young
Jorge Young 2021 年 6 月 17 日
コメント済み: Jorge Young 2021 年 6 月 17 日
Thanks in advance, I feel like this is a very simple task and I can not get the correct answer.
for the csv Vals.csv
I want to add a value of 50 if Vals.Values < 50, and subtract if Vals.Values > 50. when I try to run the example, it just returns the same values in the table.
if Vals.Values <= 50
Vals.Values = Vals.Values + 50;
else
Vals.Values = Vals.Values - 50;
end

採用された回答

SALAH ALRABEEI
SALAH ALRABEEI 2021 年 6 月 17 日
% Try this
mask = Vals.Values <= 50;
Vals(mask).Values = Vals(mask).Values + 50;
Vals(~mask).Values = Vals(~mask).Values - 50;

その他の回答 (1 件)

Cris LaPierre
Cris LaPierre 2021 年 6 月 17 日
Your code works for me, with one modification - using Vals.Value instead of Vals.Values.
One thing to be aware of, Your code works in this example because all the values are less than 50. The conditional statement in an if statement accepts a single logical outcome. When you use a logical comparison on a vector, you get a result for each comparison. Therefore, the if statement treats it as if it were written all(Vals.Value <= 50). If every coparison is true, then only the if statement code runs. If even one is false, the only the else statement code runs. Either way, only one condition is executing.
The solution is to either use a for loop to check each value one at a time, or better, use logical indexing.
ind50 = Vals.Values <= 50;
Vals.Values(ind50) = Vals.Values(ind50) + 50;
Vals.Values(~ind50) = Vals.Values(~ind50) - 50;
See Ch 12 of MATLAB Onramp.
  1 件のコメント
Jorge Young
Jorge Young 2021 年 6 月 17 日
This is great info! thank you

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

カテゴリ

Find more on Matrices and Arrays in Help Center and File Exchange

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by