フィルターのクリア

Not performing an if statement if a certain value is selected

8 ビュー (過去 30 日間)
Jake keogh
Jake keogh 2021 年 2 月 12 日
コメント済み: Jake keogh 2021 年 2 月 12 日
I am writing a function which calculates an average value, for the values 1-4, which the user selects earlier, the code can continue fine, however if the user selects five, I do not want the code to be carried out. I have tried return but that does not work.
Here is the function:
function [avg] = avg_wins(team)
if team == 1
avg = readtable('Arsenal.xlsx');
elseif team == 2
avg = readtable('Liverpool.xlsx');
elseif team ==3
avg = readtable('ManchesterUnited.xlsx');
elseif team == 4
avg = readtable('Chelsea.xlsx');
elseif team == 5
return
end
x = sum(avg{:,2})/12;
fprintf('Average wins per season = %d\n',round(x))
end
Thanks for any help

採用された回答

Walter Roberson
Walter Roberson 2021 年 2 月 12 日
The difficulty you are having is that when you return from a function (whether through return statement or by reaching the end of the flow), you need to have assigned values to any output variables that the user's code expects to be present. You cannot just return from avg_wins upon team 5 because the context needs avg to have been given a value. Some value. Any value.
If you do not wish to return a value, then you have to cause MATLAB to create an error condition using error() or throw() (or rethrow() ) . The caller's code will see the error condition and react to it, typically by giving an error message and stopping execution, but code can use try/catch to manage errors if it wants to.
  3 件のコメント
Walter Roberson
Walter Roberson 2021 年 2 月 12 日
function [avg] = avg_wins(team)
if team == 1
avg = readtable('Arsenal.xlsx');
elseif team == 2
avg = readtable('Liverpool.xlsx');
elseif team ==3
avg = readtable('ManchesterUnited.xlsx');
elseif team == 4
avg = readtable('Chelsea.xlsx');
else
avg = table([]);
fprintf('Wrong team, must be 1, 2, 3, or 4\n');
return
end
x = sum(avg{:,2})/12;
fprintf('Average wins per season = %d\n',round(x))
end
But are you sure you want to return the entire set of data about the team, but not return the number of average wins that you carefully calculated and put into x ?
Jake keogh
Jake keogh 2021 年 2 月 12 日
Thanks Walter,
does exactly what I need it to.

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

その他の回答 (0 件)

カテゴリ

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