Uniformly Distribute numbers on for loop?

1 次查看(过去 30 天)
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?

采纳的回答

OCDER
OCDER 2017-10-12
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 个评论
Matt Amador
Matt Amador 2017-10-12
OH! Now, I see what you meant there! Sorry for not looking at it more closely, but now I understand what I did wrong here. Thank you so much for the help! (:

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Line Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by