How to calculate each result of f(x) in the nested for loop?

1 view (last 30 days)
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
Jan on 25 Nov 2020
"Still not working" does not clarify, what you consider as problem. The second code is running without an error.

Sign in to comment.

Accepted Answer

Jan
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

Sign in to comment.

More Answers (1)

Walter Roberson
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
ZIYI WENG
ZIYI WENG on 26 Nov 2020
Thank you, but the graph I need to draw is supposed to look like this :
x-axis: x(scale from 1 to 180)
y-axis: a
Walter Roberson
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)

Sign in to comment.

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!