Assignment error only occuring within a while loop

So I'm getting what I hear is quite a common MATLAB eror, "In an assignment A(I) = B, the number of elements in B and I must be the same." on line 25 of my code (the line: answer2(f)=(1/f)*sin(f*x);)
The code is:
function b=evaluatesum(x,n)
answer1=[];
for z=1:2:n
answer1(z)=(1/z)*sin(z*x);
end
b=(4/pi)*sum(answer1);
disp(b)
clf
x=0:pi/3:8*pi;
f1=(4/pi)*(1/3)*sin(3*x);
f2=(4/pi)*(1/33)*sin(33*x);
f3=(4/pi)*(1/99)*sin(99*x);
f4=sin(x);
hold on
plot(x,f1,'r--')
plot(x,f2,'g')
plot(x,f3, 'b--')
plot(x,f4)
legend('f1','f2','f3','f4')
n=0;
answer=0;
answer2=[];
while abs(answer-1)>(1/1000)
for f=1:2:n
answer2(f)=(1/f)*sin(f*x);
end
answer=sum(answer2)*(pi/4);
n=n+2;
end
disp(n-2)
end
I'm not sure why I'm getting the error. Also, when I remove the while loop, it runs just fine, there is no problem with the assignment. I'm not sure why the while loop would impact this at all?
Andrew

 Accepted Answer

Your x is a vector and your f is a scalar, so f*x is a vector and sin(f*x) is a vector and (1/f) times that is a still a vector. And you attempt to store that vector into the single location answer2(f).
When you do the sum() after the loop, are you expecting that to total over the f, or over the x? If you are expecting it to total over the x, then use
answer2(f) = sum((1/f)*sin(f*x));
inside the loop and then remove the sum() outside the loop. But if you are expecting it to total over the f, then instead of initializing answer2=[], initialize answer2 = zeros(size(x)) and then in the loop,
answer2 = answer2 + (1/f)*sin(f*x);
and remove the sum() after the loop.

More Answers (0)

Categories

Find more on Parallel Computing in Help Center and File Exchange

Products

Tags

Community Treasure Hunt

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

Start Hunting!