I need help with matrix size confliction in code

function [xx,tt] = syn_sin(fk, Xk, fs, dur, tstart)
xx = 0;
M = length(fk);
Ts = 1/(fs);
s1 = fs*tstart;
s2 = fs*(dur + tstart);
n = s1:s2;
w = 2*pi*fk(1:M);
tt = (n*Ts);
x = real(Xk(1:M).*exp(j*w.*tt));
xx = xx + x;
plot(tt,xx);
So I'm getting this error: (ignore the line # I had comments in between the code)
Error using .*
Matrix dimensions must agree.
Error in syn_sin (line 58)
x = real(Xk(1:M).*exp(j*w.*tt));
Error in Untitled2 (line 8)
syn_sin([0,100,250],[10,14*exp(-j*pi/3),8*j],10000,0.1,0);
I'm basically trying to create a sin graph using the summation of A*E(jwt) but I can't get the vectorization method to work. I can use a for loop and it works but I'm trying to avoid using that. Any thoughts?
edit: fk, Xk, and w has 3 values and n and tt has 1001. The size confliction seems to not matter in a for loop but I can't get it to work when I vectorize it.

 Accepted Answer

The error refers to the element-by-element multiplication "w.*tt". You are attempting to multiply the three elements of row vector 'w' by the thousand and one elements of 'tt', which doesn't make sense in matlab's syntax.
You mention "size confliction seems to not matter in a for loop", so my guess is that you wish to plot three different curves of 1001 points each, which is to say three different frequencies with 1001 time points each, but that is not what your attempt at vectorization accomplishes. You should state clearly what it is you are trying to do, so we wouldn't have to guess at it.

5 Comments

Sorry I should of been more clear. Yes you're right about the multiple plots. I have an array of 3 (or more) frequencies and amplitudes (3 different cos waves) and I want to combine (concatenate) them to a single graph.
Rewrite the line for x as:
x = real(bsxfun(@times,Xk(1:M).',exp(j*w.'*tt)));
which will make x a 3-by-1001 array. Then either
plot(repmat(tt,1,3),reshape(x.',1,[]),'.') % Using plotted dots
or
for k = 1:3
plot(tt,x(k,:),'-') % Using plotted line segments
hold on
end
hold off
jerry
jerry on 8 Feb 2015
Edited: jerry on 8 Feb 2015
Ack, I guess I wasn't very clear about what I meant in combining the graphs. I wanted to add up the various cos waves so that I get a complex cos signal, not plotting them separately onto one. Sorry about that!
In that case just do a summation
x = real(bsxfun(@times,Xk(1:M).',exp(j*w.'*tt)));
plot(tt,sum(x,1))
Thank you so much! It's been quite a while since I had to code in matlab haha.

Sign in to comment.

More Answers (0)

Categories

Asked:

on 7 Feb 2015

Commented:

on 8 Feb 2015

Community Treasure Hunt

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

Start Hunting!