Passing vector argument into a function returns only one value

Hello,
I am trying to create a unit step function without the 0.5 at n = 0, to use within a bigger script. However I cannot input a simple 1D vector into it.
function [a] = ustep(n)
if n<0
a=0;
else
a=1;
end
end
And now this trial code, in which I try to pass -100:100 vector to it, in order to test it. I have useless variables just for testing purposes.
clear; close all; clc;
n = [-100:100];
signal = ustep(n);
signal1 = ustep(0:100);
stem(ustep(n));
stem(n, ustep(n)) straight up doesn't work because ustep() with a vector argument just returns 1. Which is not as sizeable as -100:100 obviously.

 채택된 답변

David Hill
David Hill 2021년 4월 3일
function [a] = ustep(n)
a=zeros(size(n));
a(n>=0)=1;
end

댓글 수: 3

Thank you very much this works beautifully. But could you please explain why the above code doesnt work? Is it because of if statements?
Several problems. When you set a=1 or a=0 your answer will always be scalar (1 or 0). n<0 provides an array of logical 1's and 0's depending on the values in n.
function [a] = ustep(n)
a=n>=0;%This will give you the same thing but with logicals
end
"Is it because of if statements?"
Yes: if you must use an IF statement on individual elements of an input array, then you would need to nest the IF inside a loop (iterating over the elements of the input array, and using appropriate indexing on the input and output arrays).
However it is much simpler to basic MATLAB vectorized operations, as David Hill showed.

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

추가 답변 (0개)

카테고리

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

질문:

2021년 4월 3일

댓글:

2021년 4월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by