Info

La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.

How do I input two different vectors, r and h, into an equation?

6 visualizaciones (últimos 30 días)
Billy Worley
Billy Worley el 2 de Mayo de 2019
Cerrada: MATLAB Answer Bot el 20 de Ag. de 2021
So I'm creating a function for C, that needs to input the first element of vector r, and the first element of vector h, and calculate the cost. I chose to create a for loop, and the first part works fine for calculating h. Once I obtain h, I use that in an equation for C that is a function of both r and h. **r is supposed to be from 2:10. ** h kept beginning with 0, so I changed my code to r+1, with r being from 1:9 to get my correct vector for h.
After this first code runs, r changes to 10. When I run my 2nd code, again r changes to 10, and my loop runs the following (r,h) values: (10, 46.xx), (10, 19.xx), etc. when it should be: (2, 46.xx), (3, 19.xx), etc. Essentially my radius should iterate 2,3,4...10 but it automatically changes to 10. How do I get it to iterate elements of both r and h?
h = 0;
for r= 1:9
h(r) = (600 - (2*pi*(r+1)*(r+1)*(r+1)/3))/(pi*(r+1)*(r+1));
end
display(h);
----------------------------------------------------------------------
C = 0;
for r= 1:9 h= h
C = 300*2*pi*(r+1)*(h) + 400*pi*(r+1)*(r+1);
end

Respuestas (1)

Raj
Raj el 2 de Mayo de 2019
I am not sure where is the issue.I have just tweaked the second half of your code a little bit. The second loop uses values of (r,h) as (2, 46.xx), (3, 19.xx), etc. and computes value of C accordingly for each combination:
C = 0;
for r= 1:9
%h= h
C = 300*2*pi*(r+1)*h(1,r) + 400*pi*(r+1)*(r+1)
end
So things look fine to me.
  2 comentarios
Billy Worley
Billy Worley el 2 de Mayo de 2019
Running this just give me one C value result, instead of the 9 it should be displaying.
Follow up question: Can you do linspace inside a for loop? Normally it iterates by 1,2,3,4, can you make it iterate by 0.5's for example? Or do you need to take another route?
Raj
Raj el 2 de Mayo de 2019
1) "Running this just give me one C value result"- The code is doing what it is supposed to do. C value gets updated for every run of the loop and in the end you get only one value which is the last value. If you want to store all the 9 values then use this (same as what you have used in your first loop):
C = 0;
for r= 1:9
%h= h
C(r) = 300*2*pi*(r+1)*h(1,r) + 400*pi*(r+1)*(r+1)
end
display(C);
2) You can change increment value of 'for' loop like this
for r=1:0.5:10 % r starts at 1 and increments in steps of 0.5 till 10

La pregunta está cerrada.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by