- Pass in the single value to your function: Sign = signum (B)
- Pass in the entire matrix, and define r and c inside the function: Sign = signum (A)
- Pass in the matrix along with r and c: Sign = signum (A,r,c)
Could someone please explain what is wrong in my function?
2 ビュー (過去 30 日間)
古いコメントを表示
I am attempting to create a fuction that takes in a matrix element and outputs with 1 0 or -1 depending on if th element is positive, zero or nagative respectively.
In the first line it underlines the first ( and , in the (A(r,c)) as well as both () around (r,c)
I am quite new so any help would be appreciated :)
function [Sign] = signum ( A(r,c) )
if A(r,c) == 0
Sign = 0;
elseif A(r,c) < 0
Sign = -1;
elseif A(r,c) > 0
Sign = 1;
end
disp(Sign);
end
0 件のコメント
採用された回答
Cris LaPierre
2021 年 6 月 9 日
You have not defined r and c.
You have three options that I see.
% Example of option 1
A = -5:5;
r = 1; c = 3;
B = A(r,c);
Sign = signum (B)
function [Sign] = signum (B)
if B == 0
Sign = 0;
elseif B < 0
Sign = -1;
elseif B > 0
Sign = 1;
end
end
2 件のコメント
Cris LaPierre
2021 年 6 月 9 日
The function will only do what you have coded it to do. Passing in an entire matrix will not automatically test every element. You would have to write you code in such a way that it tests every element.
You can call the function using A(r,c), but you can not declare your function input using that notation.
% Example of option 1
A = -5:5;
r = 1; c = 3;
Sign = signum (A(r,c))
function [Sign] = signum (B)
if B == 0
Sign = 0;
elseif B < 0
Sign = -1;
elseif B > 0
Sign = 1;
end
end
その他の回答 (2 件)
David Hill
2021 年 6 月 9 日
Why not just use built-in function sign()?
a=sign(A);
%then index into a for specific element
Jan
2021 年 6 月 9 日
function [Sign] = signum(A)
The indices (r,c) belongs to the caller of the function, not inside the function. You call this function by:
signum(A(r,c))
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!