How can I get the return of a constructed function as an array?

The constructed function is
function [a] = triangle(n)
a=zeros(size(n));
if (n>=0 & n<=pi) % use an if else statement to execuete
a = pi-n;
else
a = 0; %n; % 0 otherwise
end
end
It can be used with integral function very well. But when I input x = -3:0.01:3, the return velue is 0.
>> x = -3:0.01:3;
>> triangle(x)
ans =
0
>>

 Accepted Answer

That is not how MATLAB works. Your code defines a matrix of zeros, but then you do nothing with that variable and simply replace that variable with some other data. Your code also does not take into account the requirements for the IF condition to be considered TRUE (read the IF documentation carefully, if you are interested). If you use IF /ELSE for this then you would need to use a loop and indexing, but your code has neither of these.
In any case, the MATLAB approach is not to use IF/ELSE, but to use logical indexing, e.g.:
x = -3:0.01:3;
y = triangle(x)
y = 1×601
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
nonzeros(y)
ans = 301×1
3.1416 3.1316 3.1216 3.1116 3.1016 3.0916 3.0816 3.0716 3.0616 3.0516
function a = triangle(n)
a = zeros(size(n));
x = n>=0 & n<=pi;
a(x) = pi-n(x);
end
Read more:

1 Comment

Thank you very much. Everything works correctly. I will read the document you suggested.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!