How I can solve the problem of Loop?

조회 수: 14 (최근 30일)
Anu Sharma
Anu Sharma 2022년 8월 28일
이동: Voss 2024년 11월 6일 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?

채택된 답변

Walter Roberson
Walter Roberson 2022년 8월 28일
이동: Voss 2024년 11월 6일 21:54
Y=X+9+26

추가 답변 (1개)

Arjun
Arjun 2024년 11월 6일 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!

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by