How do I fill arrays with a for loop?
Show older comments
I'm trying to calculate the values for x and y that make z=3^x/2^y as close to 1 as possible using this code
x(1) = 1;
y(1) = 1;
z(1) = 3^x(1)/2^y(1);
for a = 2:20
if z > 1
y(a) = y(a-1)+1
x(a) = x(a-1)
z(a) = 3^x(a)/2^y(a)
end
if z < 1
x(a) = x(a-1)+1
y(a) = y(a-1)
z(a) = 3^x(a)/2^y(a)
end
end
and I'm only getting the first 2 values for x, y, and z. What is the appropriate way of doing this? I managed to calculate z just fine when it was just a scalar but now that I'm trying to fill arrays it isn't working.
Answers (1)
Star Strider
on 2 May 2018
I would test the current value of ‘z’ in your if blocks:
z(a-1) > 1
and:
z(a-1) < 1
respectively.
That will solve the problem of your code only returning two values.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!