User-defined function error

I'm trying to write a function for this problem on my homework and keep getting an error and I'm not sure whats wrong with my code.
7. Write a user-defined function in Matlab of the form B=sqrtIfPos(A) that accepts a real-valued 2D matrix A of an arbitrary size (MxN), and outputs the same size (MxN) matrix B whose elements are square root for positive-valued elements of A, and 0 for negative-valued elements. For example, an input of [4 9 -3; 1 0 16] would produce an output of [2 3 0; 1 0 4] . Test the function with a 3x5 matrix of random integers in the interval [-10,10], which can be generated by randi([-10,10],3,5).
This is what I have so far:
function B=sqrtIsPos(A)
[m, n]=size(A);
B=zeros(m,n);
for i=1:m
for j=1:n
if (A(i,j)>=0)
B(i,j)=sqrt(A(i,j));
else
B(i,j)=0;
end
end
end
end
A=randi([-10,10],3,5)
B=sqrtIsPos(A)
print sqrtIfPos.m

3 件のコメント

Matt J
Matt J 2018 年 10 月 30 日
Have you put the function sqrtIsPos somewhere Matlab can see it?
Stephen23
Stephen23 2018 年 10 月 30 日
編集済み: Stephen23 2018 年 10 月 30 日
@Emily Williams: what do you expect this to do?:
print sqrtIfPos.m
Is all of that code saved in one Mfile, or is the function sqrtIsPos saved in its own Mfile?
Emily Williams
Emily Williams 2018 年 10 月 30 日
sprtIsPos is saved in its own mfile. I'm supposed to use the function in a different mfile thats my homework, and print sqrtIfPos.m should print the contents of the function in my homework.

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

回答 (2 件)

Star Strider
Star Strider 2018 年 10 月 30 日

0 投票

The only thing wrong is that you are likely not saving your function before you call it.
Save it somewhere on your MATLAB user path as sqrtIsPos.m. Then, you should be able to use it.

2 件のコメント

Emily Williams
Emily Williams 2018 年 10 月 30 日
I made sure to save it like that. It gives me an error what says: "Undefined function 'sqrtIsPos' for input arguments of type 'double'."
Star Strider
Star Strider 2018 年 10 月 30 日
Where exactly did you save it? I refer you to: What Is the MATLAB Search Path? (link).
Interesting. I copied your function as you posted it, saved it, and then ran it using your posted call to it:
A=randi([-10,10],3,5)
B=sqrtIsPos(A)
It is working correctly, and produced:
A =
9 -1 0 6 7
6 -1 0 3 1
0 -4 7 -3 -3
B =
3 0 0 2.4495 2.6458
2.4495 0 0 1.7321 1
0 0 2.6458 0 0

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

madhan ravi
madhan ravi 2018 年 10 月 30 日
編集済み: madhan ravi 2018 年 10 月 30 日

0 投票

A=[4 9 -3; 1 0 16]
B=sqrtIsPos(A) % function calling should be before the function definition
function B=sqrtIsPos(A)
[m, n]=size(A);
B=zeros(m,n);
for i=1:m
for j=1:n
if (A(i,j)>=0)
B(i,j)=sqrt(A(i,j));
else
B(i,j)=0;
end
end
end
end

1 件のコメント

madhan ravi
madhan ravi 2018 年 10 月 30 日
use
publish('sqrtIsPos.m') %to print contents of function as pdf

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

カテゴリ

質問済み:

2018 年 10 月 30 日

コメント済み:

2018 年 10 月 30 日

Community Treasure Hunt

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

Start Hunting!

Translated by