Logical indexing for two conditions

2 ビュー (過去 30 日間)
Ritika Srinivasan
Ritika Srinivasan 2022 年 11 月 8 日
コメント済み: Jan 2022 年 11 月 8 日
Hi I have this code:
Excess=zeros(size(Energy));
for i=1:length(Energy)
if Energy(i)>= 20
Excess(i)=Energy(i)-20;
end
end
I would like to replace the for loop using logical indexing. I would appreciate any help.
Best Regards,
Ritika

採用された回答

Jan
Jan 2022 年 11 月 8 日
編集済み: Jan 2022 年 11 月 8 日
Excess = zeros(size(Energy));
m = (Energy >= 20);
Excess(m) = Energy(m) - 20;
A simpler code, but without the wanted logical indexing:
Excess = max(0, Energy - 20);
  3 件のコメント
Ritika Srinivasan
Ritika Srinivasan 2022 年 11 月 8 日
Hey @Jan could you please explain what this command does : Excess = max(0, Energy - 20); I would like to understand how it works or if you have any documentation to support that
Jan
Jan 2022 年 11 月 8 日
Of course you can read the documentation of this command:
help max
doc max
Searching in the internet for "Matlab max" displays the online help: https://www.mathworks.com/help/matlab/ref/max.html
Matlab's documentation is very useful and much better than other manuals e.g. the help sections of Windows :-)
If a command does not do exactly, what you need, look at the "See also" line at the bottom, which suggests similar commands.

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by