How I can solve the problem of Loop?

15 ビュー (過去 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!
  1 件のコメント
Walter Roberson
Walter Roberson 2024 年 11 月 6 日 21:46
Or you can do the much shorter
Y=X+9+26

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by