How I can solve the problem of Loop?
14 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
更多回答(1 个)
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’:
- for:https://www.mathworks.com/help/releases/R2022a/matlab/ref/for.html
- if-elseif-else: https://www.mathworks.com/help/releases/R2022a/matlab/ref/if.html
I hope this will help!
1 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!