フィルターのクリア

Why will one of my lines of this function not work?

1 回表示 (過去 30 日間)
James Crowe
James Crowe 2017 年 11 月 21 日
コメント済み: James Crowe 2017 年 11 月 21 日
How comes the line elseif p == 2 doesn't work when using the function in a script, but the rest do? Is there a better way to do this? Also how would I make it so that there is no output to the command window?
function [detA,trA] = myFunction(A,p)
if p == 1
detA = det(A);
elseif p == 2
trA = trace(A);
else
disp ('Invalid input')
end

採用された回答

Birdman
Birdman 2017 年 11 月 21 日
You define 2 outputs but in each if case, you only use one output and the other one is left unassigned. When you call function from workspace by not assigning its outputs, like
myFunction(A,1)
or
myFunction(A,2)
it automatically returns the first output. Since in the second if case you did not assign the first output to something, it does not return it. Instead try the following.
function y = myFunction(A,p)
if p == 1
y= det(A);
elseif p == 2
y= trace(A);
else
disp ('Invalid input')
end
and you can call it by
myFunction(A,1)
or
myFunction(A,2)
  1 件のコメント
James Crowe
James Crowe 2017 年 11 月 21 日
Ah, that makes sense! Brilliant thank you

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeOrdinary Differential Equations についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by