Could someone please explain what is wrong in my function?

조회 수: 2 (최근 30일)
Sergey Popov
Sergey Popov 2021년 6월 9일
댓글: Sergey Popov 2021년 6월 9일
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

채택된 답변

Cris LaPierre
Cris LaPierre 2021년 6월 9일
You have not defined r and c.
You have three options that I see.
  1. Pass in the single value to your function: Sign = signum (B)
  2. Pass in the entire matrix, and define r and c inside the function: Sign = signum (A)
  3. Pass in the matrix along with r and c: Sign = signum (A,r,c)
% Example of option 1
A = -5:5;
r = 1; c = 3;
B = A(r,c);
Sign = signum (B)
Sign = -1
function [Sign] = signum (B)
if B == 0
Sign = 0;
elseif B < 0
Sign = -1;
elseif B > 0
Sign = 1;
end
end
  댓글 수: 2
Sergey Popov
Sergey Popov 2021년 6월 9일
Thank you so much I was under the impression that you are able to pass a matrix in with custom r and c values using matrix indexing but i can see now why that doesnt work. I think option 3 works best in my case since my assigment requires that a specific matrix element is tested not the whole matrix.
Out of curiousty tho will passing the whole matrix in test every element in it one by one?
Cris LaPierre
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))
Sign = -1
function [Sign] = signum (B)
if B == 0
Sign = 0;
elseif B < 0
Sign = -1;
elseif B > 0
Sign = 1;
end
end

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

David Hill
David Hill 2021년 6월 9일
Why not just use built-in function sign()?
a=sign(A);
%then index into a for specific element
  댓글 수: 1
Sergey Popov
Sergey Popov 2021년 6월 9일
I am not allowed to use it cause my proffesor wanted us to develop a manual function for this operation.
I wish tho..

댓글을 달려면 로그인하십시오.


Jan
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))

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by