Error when ploting discrete time function
5 views (last 30 days)
Show older comments
Brandon Stark
on 7 Aug 2021
Commented: Star Strider
on 9 Aug 2021
I defined an anonymous function as below
xn = @(n)[(n==-3),(n==-2),(n==-1),(n==0),(n==1),(n==2),(n==3)]*[3;2;1;0;1;2;3]
This functions means to describe a discrete signal
x[n]=[3 2 1 0 1 2 3]
^
However, when I attempted to plot a discrete figure for this signal using stem function:
n=[-3:3]
stem(n,xn(n))
Matlab gives the error message as following:
Error using *
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches
the number of rows in the second matrix. To perform elementwise multiplication, use '.*'.
Error in @(n)[(n==-3),(n==-2),(n==-1),(n==0),(n==1),(n==2),(n==3)]*[3;2;1;0;1;2;3]
I really don't know where goes wrong.
A big thanks to all that may drop by and leave your answer!
0 Comments
Accepted Answer
Star Strider
on 7 Aug 2021
Use element-wise multiplication (.*) instead of matrix multiplication (*).
Try this —
xn = @(n)[(n==-3),(n==-2),(n==-1),(n==0),(n==1),(n==2),(n==3)].*[3;2;1;0;1;2;3];
figure
n=[-3:3]
stem(n,xn(n))
.
8 Comments
More Answers (1)
Paul
on 7 Aug 2021
Edited: Paul
on 8 Aug 2021
The function definition is implicitly assuming that the input, n, is a scalar. Looking at the first the term on its LHS:
n = 2;
[(n==-3),(n==-2),(n==-1),(n==0),(n==1),(n==2),(n==3)]
That returns what you expect. But with n a vector
n = 1:2;
[(n==-3),(n==-2),(n==-1),(n==0),(n==1),(n==2),(n==3)]
Each logical comparison is the same size as n, then each of those are concatenated together. Clearly this result can't be element-multiplied with -3:0:3.
Edit: I just realized that the function in the quesion was relying on matrix mulitplication, not element mulitplication. But the point still stands that terms being multiplied are incompatible.
Fortunately, this example can be expressed in closed form
x = @(n)(abs(n).*(abs(n)<=3)); % assumes x(n) is zero for abs(n) > 3
x(-3:3)
x([-1 2])
If you have a finite duration sequence that can't be expressed in closed form, you can always just use indexing, accounting for Matlab's 1-based indexing.
x = abs(-3:3); n = -3:3;
x([-1 2]+(1-n(1)))
You can wrap this up in a function if desired, where n defines the sequence and k defines the elements of the sequence you want to return
xn = @(k,x,n)(x(k+(1-n(1))));
xn([-1 2],x,n)
xn(-1:1,x,n)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!