how to use for loop and while loop in this equation?

1 visualización (últimos 30 días)
Engineer Batoor khan mummand
Engineer Batoor khan mummand el 6 de Mzo. de 2021
Respondida: Deepak el 9 de Ag. de 2024
hi to all,
i hope you all will be fine and doing well,
(1) i have four initial values x=0, x=0.3, x=0.07 and x=0.001 i want find the values of p such that when x reaches to 1 or greather than 1.
(2) when x reaches to 1 it sholud strat again and take second intial value which is given above the programme and it should continoue till last intial value.
thanks
where x is initail value
n=8;
v=4
t=0.5
for i=1:n-1
x=0
while x<=1
itn=itn+1
p(1:n,i)=2*x+4*v
x=x+t
end
end

Respuestas (1)

Deepak
Deepak el 9 de Ag. de 2024
To my understanding, you want to take four initial values of variable ‘x’ and then increment ‘x’ with a fixed step ‘t’ each time. When x reaches or exceeds 1, you want to calculate the value of ‘p’ and store in an array. This task needs to be done for each initial value of ‘x’.
To do this task, we can create an array ‘initial_values’ that will store the initial values of ‘x’. Then, we will iterate over this array with the help of a for loop, and in each iteration, we will assign the current array element to ‘x’.
Then, we can increment the value of ‘x’ with fixed step ‘t’ with the help of a while loop.
Finally, after the while loop, we can calculate the value of ‘p’ and store it in the answer array and display that array.
Here is the MATLAB code that addresses this task:
% Given initial values
initial_values = [0, 0.3, 0.07, 0.001];
n = length(initial_values);
v = 4;
t = 0.5;
p = [];
itn = 0; % Iteration counter
for idx = 1:n
x = initial_values(idx); % Set the initial value of x
while x < 1
x = x + t; % Increment x by t
end
% Calculate p when x reaches or exceeds 1
itn = itn + 1;
p(itn) = 2 * x + 4 * v;
end
disp('Values of p:');
disp(p);
Attaching the documentation of loop control statements in MATLAB for reference –
I hope this helps to resolve your issue.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by