How I can solve the problem of Loop?

14 visualizaciones (últimos 30 días)
Anu Sharma
Anu Sharma el 28 de Ag. de 2022
Movida: Voss el 6 de Nov. de 2024 a las 21:54
N = 15
X = randi([1,3],[N,1]);
X will be 15 by 1 matrix with random values 1, 2, 3.
Y1 = 10 (For X = 1)
Y2 = 11 (For X = 2)
Y3 = 12 (For X = 3)
I want to find the value of Y for every value of X such that Y = Y1 +26 (for X = 1), Y = Y2+26 (For X = 2) and Y = Y3 +26 (For X =3)
For every value of X i want to calculate the value of Y that depends upon Y1, Y2 and Y3
Moreover, resultant Y will be a single matrix, how I can use the loop?

Respuesta aceptada

Walter Roberson
Walter Roberson el 28 de Ag. de 2022
Movida: Voss el 6 de Nov. de 2024 a las 21:54
Y=X+9+26

Más respuestas (1)

Arjun
Arjun el 6 de Nov. de 2024 a las 10:42
I see that you have variables ‘X’, ‘Y1’, ‘Y2’ and ‘Y3’ and want to estimate the value of ‘Y’ which will be a Nx1 matrix.
You can estimate the values of ‘Y’ using a simple ‘for’ loop combined with an ‘if-elseif-else’ construct to model the equations based on the values of ‘X’.
The general flow of the code will look something like this:
  • Initialize variables ‘X’, ‘Y1’, ‘Y2’ and ‘Y3’.
  • Initialize variable ‘Y’ with dummy values in the start.
  • Implement ‘for’ loop and apply ‘if-elseif-else’ construct to build logic.
  • Populate the values of ‘Y’ and display them.
Please refer to the code below for better understanding:
% Declare the variables
N = 15;
X = randi([1, 3], [N, 1]);
Y1 = 10;
Y2 = 11;
Y3 = 12;
% Initialize Y as a column vector of zeros with the same size as X
Y = zeros(N, 1);
% Loop through each element of X to calculate the corresponding Y value
for i = 1:N
if X(i) == 1
Y(i) = Y1 + 26;
elseif X(i) == 2
Y(i) = Y2 + 26;
elseif X(i) == 3
Y(i) = Y3 + 26;
end
end
% Display the result
disp('X:');
disp(X);
disp('Y:');
disp(Y);
Kindly refer to documentation of ‘for’, ‘if-elseif-else’:
I hope this will help!

Categorías

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

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by