How I can solve the problem of Loop?

14 Ansichten (letzte 30 Tage)
Anu Sharma
Anu Sharma am 28 Aug. 2022
Verschoben: Voss am 6 Nov. 2024 um 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?

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 28 Aug. 2022
Verschoben: Voss am 6 Nov. 2024 um 21:54
Y=X+9+26

Weitere Antworten (1)

Arjun
Arjun am 6 Nov. 2024 um 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!

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by