Error when ploting discrete time function
Mostra commenti meno recenti
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!
Risposta accettata
Più risposte (1)
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)
7 Commenti
Brandon Stark
il 9 Ago 2021
Paul
il 9 Ago 2021
Can you provide a simple example that illustrates what doesn't work?
Brandon Stark
il 9 Ago 2021
As shown above:
xn = @(k,x,n)(x(k+(1-n(1))));
x = [1 0 0 3 4 0 0 6]; % the sequence
n = -3:4; % its indices
% examples
xn(-3:4,x,n)
xn([-3 -2],x,n)
xn([-3 0 1],x,n)
Of course, this approach does not gracefully handle the situation where the requested indices are outside the bounds of the defined sequence
xn(-4,x,n)
Brandon Stark
il 9 Ago 2021
You can also wrap up the sequence in a structure to simplify things a bit:
x.vals = [1 0 0 3 4 0 0 6];
x.indices = -3:4;
xn = @(n,sequence)(sequence.vals(n+(1-sequence.indices(1))));
xn([-3 0 1],x)
Brandon Stark
il 9 Ago 2021
Categorie
Scopri di più su Mathematics in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


