0

I have been thrown in the deep end in one of my Signals classes. I am trying to learn Octave so that I can do the Matlab assignments required by the professor at home (I have not had any education in Matlab yet).

I have been reading as much as I can but I cannot seem to figure out why this function only seems to return 0. I think I am missing something fundamental but I don't know what.

t = [-1:0.1:5];

% (a): The Unit-step Function u(t)
function u = u (t)
    if(t >= 0)
        u = 1;
    else
        u = 0;
    end
end

plot(t, u(t));
1
  • Because u in your function is a scalar not a vector. Try initializing u = zeros(size(t)), and u(t>=0) = 1. That should do it. Commented Jun 7, 2017 at 1:44

1 Answer 1

1

The problem arises because the function enters a vector and returns a scalar, so plot draws erroneously.

One solution:

A possible solution is to create the new vector with zeros (), and then iterate with for by selecting the output with the if.

t = [-1:0.1:5];

% (a): The Unit-step Function u(t)
function u = u (t)
    u = zeros(size(t));
    for i=1:length(t)
        if(t(i) >= 0)
            u(i) = 1;
        else
            u(i) = 0;
        end
    end
end
plot(t, u(t));

Second solution:

Another solution is to use the properties of matlab/octave to handle vector operations.

t = [-1:0.1:5];

% (a): The Unit-step Function u(t)
function u = u (t)
    u = t>=0
end
plot(t, u(t));
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! That makes perfect sense. Also, the second solution is very clever.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.