if and for loop

2 ビュー (過去 30 日間)
adarsh
adarsh 2018 年 1 月 8 日
コメント済み: Walter Roberson 2024 年 10 月 22 日
How to write a program for the following statements:
Cpv=0 if vi is less than equal to 10
15
Cpv=(1/15)(Vi^2-100) if vi is more than 10
i=1
Cpp=0 if Pj is greater than or equal to 18
50
Cpp=(18-Pj) if Pj is less than 18
j=1
kindly help me out. Thanks in advance

回答 (1 件)

BhaTTa
BhaTTa 2024 年 10 月 22 日
編集済み: Walter Roberson 2024 年 10 月 22 日
Hey @adarsh, you can implement it with couple of if conditions and sum function, below i have attahced the code implementing the same:
% Example input vectors
Vi = [5, 12, 9, 15, 11, 8, 14, 13, 10, 7, 16, 6, 18, 4, 20]; % Length 15
Pj = [20, 17, 19, 15, 16, 18, 14, 13, 22, 21, 17, 19, 16, 18, 20, 15, 14, 17, 16, 18]; % Length 50
% Calculate Cpv
if all(Vi <= 10)
Cpv = 0;
else
Cpv = (1/15) * sum(Vi(Vi > 10).^2 - 100);
end
% Calculate Cpp
if all(Pj >= 18)
Cpp = 0;
else
Cpp = sum(18 - Pj(Pj < 18));
end
% Display the results
fprintf('Cpv: %.2f\n', Cpv);
Cpv: 69.00
fprintf('Cpp: %.2f\n', Cpp);
Cpp: 28.00
Hope it helps.
  2 件のコメント
Voss
Voss 2024 年 10 月 22 日
You don't need the if conditions because sum([]) is 0.
Walter Roberson
Walter Roberson 2024 年 10 月 22 日
If the sum() were 0 then one of Cpv or Cpp would ahve come out as 0, but neither one does.

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by