How to calculate each result of f(x) in the nested for loop?
1 view (last 30 days)
Show older comments
This might be a quite simple question but I am really a starter. Hope to get help from you guys, thanks a lot!
I need to calculate different results of f(x) while x equals 1 to 180 to plot a graph.
Firstly , I wrote the nested loop:
j = sqrt(-1);
for x = 1:180
for i = 1:5
f(x)=f(x) + exp((-j).*(i-1).*sin(x))
end
end
Then I think I need to do the pre-allocating, so I change the f(x) to :
j = sqrt(-1);
a = zeros(180,5);
for x = 1:180
for i = 1:5
a(x,i)=a(x,i)+ exp((-j).*(i-1).*sin(x))
end
end
However, it is still not working, what should I do?
1 Comment
Jan
on 25 Nov 2020
"Still not working" does not clarify, what you consider as problem. The second code is running without an error.
Accepted Answer
Jan
on 25 Nov 2020
Edited: Jan
on 25 Nov 2020
This is correct, but not useful:
j = sqrt(-1);
i and j are defined as imaginary units as default already. But you see the ambiguities with using variables with the same name. So prefer 1j or 1i.
for x = 1:180
for i = 1:5
f(x)=f(x) + exp((-j).*(i-1).*sin(x))
end
end
This fails an error message, because f(x) is undefinde in the first call. So replace it by:
f = zeros(1, 100);
for x = 1:180
s = 0;
for i = 1:5
s = s + exp(-1j .* (i-1) * sin(x));
end
f(x) = s;
end
Or convert the inner loop to a vector operation:
f = zeros(1, 100);
for x = 1:180
f(x) = sum(exp(-1j .* ((1:5)-1) * sin(x)));
% sum(exp(-1j .* (0:4) * sin(x)))
end
The outer loop can be vectorized also:
f = sum(exp(-1j .* (0:4).' * sin(1:180)));
4 Comments
More Answers (1)
Walter Roberson
on 25 Nov 2020
j = 1j;
x = 1:180;
i = (1:5).';
a = sum( exp(-j).*(i-1).*sind(x), 1);
plot(x, real(a), 'k', x, imag(a), 'r')
2 Comments
Walter Roberson
on 26 Nov 2020
j = 1j;
x = 1:180;
i = (1:5).';
a = sum( exp(-j).*(i-1).*sind(x), 1);
plot(x, real(a), 'k', x, imag(a), 'r'); xlim([0 180])Y
Your a is complex-valued, so you cannot use it as the y coordinate. You can use real(a) or imag(a) or abs(a) or angle(a)
See Also
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!