Uniformly Distribute numbers on for loop?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Matt Amador
am 12 Okt. 2017
Kommentiert: OCDER
am 12 Okt. 2017
Hello, I have some trouble with my code. The objective of it is to calculate
y(x) = x^3 - sin(x+pi/2) + cos^2*(2x)
for 100 values of x uniformly distributed between -1 and 3 using both a for loop, and vectorization, and to plot the two outputs.
Here is my code.
rng(0, 'Twister');
a = -1;
b = 3;
r = (b-a).*rand(100,1) + a;
pi = 3.14;
for x = r
y(x) = (x.^3) - sin*(x + (pi/2)) + cos.^2*(2*x);
end
plot(y(x))
I keep getting an error that says there is not enough input arguments for sin and cos. Can anyone help out?
0 Kommentare
Akzeptierte Antwort
OCDER
am 12 Okt. 2017
Here's the vectorized form:
rng(0, 'Twister');
a = -1;
b = 3;
x = randi([a, b], 100, 1);
y = (x.^3) - sin(x + (pi/2)) + cos(2*x).^2;
plot(x, y)
See comments to understand how to fix your for-loop-version of this:
%r = (b-a).*rand(100,1) + a; this can be replaced with randi
%pi = 3.14; don't override pi, which is Matlab constant for pi
y = zeros(size(r)); %preallocate y to improve speed
for x = r % In common practice, the for loop counter should be a vector of integers, EX k = 1:numel(r).
% Then in your code, you refer to r(k) instead of x.
% With your current x=r, you'll get ERROR: Index must be a positive integer or logical.
% Why? because if x(1) = 0.343, Matlab cannot access the 0.343th element of y in y(x) = ...
%Note: y(x) should be y(k) instead, where k is the integer for-loop counter.
y(x) = (x.^3) - sin*(x + (pi/2)) + cos.^2*(2*x); %cannot do sin*(...) or cos.^2(...)
end
plot(y(x)) %Specify the x and y to plot.
%Currently, this will give you Index Error or it'll plot 1 point since x is 1 value.
4 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Line Plots finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!