using for loop to solve a function
์ด์ ๋๊ธ ํ์
Given the following function ??(??) = 20000 * log(x) โ 3x Use a for loop to compute f(x) for 1 โค x โค 20.
my solution
x = linspace(0,20,20);
for i=1:20
x2 = x;
y2 = 20000*log(x)-3*x;
plot(x2,y2,'r')
am i on the right track plot is blank
๋ต๋ณ (1๊ฐ)
madhan ravi
2019๋
1์ 27์ผ
ํธ์ง: madhan ravi
2019๋
1์ 27์ผ
I know it is your homwork and appreciate that you have tried something.
Loop version:
x = linspace(0,20,20);
% ^^------ increase to get a smoother curve
y2=zeros(size(x)); % preallocate
for k=1:numel(x)
% x2 = x; ?? does nothing
y2(k) = 20000*log(x(k))-3*x(k);
% ^^^------ save y2 in each iteration
end
plot(x,y2,'r') % plot outside the loop
Matlab's way (vectorization):
x = linspace(0,20,20); % just three lines of code
y2 = 20000*log(x)-3*x;
plot(x,y2,'r')
๋๊ธ ์: 11
caroline
2019๋
1์ 27์ผ
caroline
2019๋
1์ 27์ผ
ํธ์ง: madhan ravi
2019๋
1์ 27์ผ
madhan ravi
2019๋
1์ 27์ผ
numel(x) gives number of elements in x ,
The best part in MATLAB is whenever you have a doubt just type
help numel % will give you detailed description of the command
doc numel
caroline
2019๋
1์ 27์ผ
caroline
2019๋
1์ 27์ผ
madhan ravi
2019๋
1์ 27์ผ
use hold on after the first plot command
caroline
2019๋
1์ 27์ผ
ํธ์ง: madhan ravi
2019๋
1์ 27์ผ
madhan ravi
2019๋
1์ 27์ผ
ํธ์ง: madhan ravi
2019๋
1์ 27์ผ
I got two questions:
1) The original question you asked was about for loops ?
2) Why do you say itโs wrong ? Each graph represents different function.
caroline
2019๋
1์ 27์ผ
madhan ravi
2019๋
1์ 28์ผ
ํธ์ง: madhan ravi
2019๋
1์ 28์ผ
You didn't answer my first question.Plus I don't see any differences in the figure? not sure what do you mean by "i just thought it was wrong because when plotted on calc it looked wrong. " Did you verify the scale?
caroline
2019๋
1์ 28์ผ
์นดํ ๊ณ ๋ฆฌ
๋์๋ง ์ผํฐ ๋ฐ File Exchange์์ Graphics Performance์ ๋ํด ์์ธํ ์์๋ณด๊ธฐ
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!