필터 지우기
필터 지우기

Uniformly Distribute numbers on for loop?

조회 수: 1 (최근 30일)
Matt Amador
Matt Amador 2017년 10월 12일
댓글: OCDER 2017년 10월 12일
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! (:
OCDER
OCDER 2017년 10월 12일
You're welcome!

댓글을 달려면 로그인하십시오.

추가 답변 (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