Hello, I'm an extreme newbie to MatLab. I'm trying to write a function that checks whether an input is square, and returns 1 for true, 0 for false. I figured that the best way to do this would be to run sqrt on each variable, then use mod to determine whether the remainder is 0. Here's the code I'm trying:
function y = issquare(n)
x = sqrt(n)
if mod (x,1)==0
y=true
else
y=false
end
The problem arises when a vector is input. Instead of returning the answers for individual vectors, it is returning a single answer. The x variable calculates correctly and returns the individual square roots of each value in the vector. The issue seems to arise when the program determines the y variable. I tried changing the mod input to
mod(x.,1)
but received an error.
Error: File: issquare.m Line: 3 Column: 11
Expression or statement is incorrect--possibly unbalanced (, {, or [.

 채택된 답변

Jan
Jan 2015년 9월 20일
편집: Jan 2015년 9월 20일

0 개 추천

Appending a dot behind a variable is not valid Matlab syntax. Please look in the documentation for valid commands, because guessing will not be successful.
The problem is, that the if command requires a scalar expression. This can be solved by a vectorized expression:
function y = issquare(n)
y = (mod(sqrt(n), 1) == 0);
Now the output has the same size as the input.

댓글 수: 2

thefaded
thefaded 2015년 9월 20일
I was only trying this because it seems to be the operator for array multiplication, division and exponentiation. I'm really new to programming. I didn't even think about nesting the expression that way. Thank you!
Jan
Jan 2015년 9월 22일
You are welcome to the world of vectorized programming in Matlab!
The dot in ".*", "./" and ".^" means, that the operation should not affect the complete matrix, but the elements. In consequence, there is e.g. no ".+", because the addition concerns the elements in every case.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Function Creation에 대해 자세히 알아보기

질문:

2015년 9월 20일

댓글:

Jan
2015년 9월 22일

Community Treasure Hunt

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

Start Hunting!

Translated by