how to create for loop in below formula
4 次查看(过去 30 天)
显示 更早的评论
Lc1 = LP1;
Lc2 = LP2-Lc1;
Lc3 = LP3-(Lc1+Lc2);
Lc4 = LP4-(Lc1+Lc2+Lc3);
Lc5 = LP5-(Lc1+Lc2+Lc3+Lc4);
Lc6 = LP6-(Lc1+Lc2+Lc3+Lc4+Lc5);
0 个评论
回答(4 个)
Ishit
2023-6-16
Hi Devaki, Use this to get desired results
LP = [LP1, LP2, LP3, LP4, LP5, LP6]; % define the LP values
Lc = zeros(size(LP)); % preallocate the Lc array
for i = 1:numel(LP)
if i == 1
Lc(i) = LP(i);
else
Lc(i) = LP(i) - sum(Lc(1:i-1));
end
end
0 个评论
Saurabh
2023-6-16
编辑:Saurabh
2023-6-16
% Define the LP values
LP = [LP1, LP2, LP3, LP4, LP5, LP6];
% Initialize the array to store the results
Lc = zeros(1, 6);
% Loop through the LP values and calculate the Lc values
for i = 1:6
if i == 1
Lc(i) = LP(i);
else
Lc(i) = LP(i) - sum(Lc(1:i-1));
end
end
%Hope this was helpful
0 个评论
Stephen23
2023-6-16
Your inefficient approach (with anti-pattern numbered variable names):
LP1 = rand;
LP2 = rand;
LP3 = rand;
LP4 = rand;
LP5 = rand;
LP6 = rand;
Lc1 = LP1
Lc2 = LP2-Lc1
Lc3 = LP3-(Lc1+Lc2)
Lc4 = LP4-(Lc1+Lc2+Lc3)
Lc5 = LP5-(Lc1+Lc2+Lc3+Lc4)
Lc6 = LP6-(Lc1+Lc2+Lc3+Lc4+Lc5)
The MATLAB approach (with vectors):
LP = [LP1,LP2,LP3,LP4,LP5,LP6];
Lc = LP;
for k = 2:numel(LP)
Lc(k) = LP(k)-sum(Lc(1:k-1));
end
disp(Lc)
The best approach:
Lc = [LP(1),diff(LP)]
Why do you keep deleting and then reposting this exact question? Or were those classmates of yours?
0 个评论
Malay Agarwal
2023-6-16
编辑:Malay Agarwal
2023-6-16
Hi, Devaki
You can use the following code, which generalizes it to a vector of any size:
% Declare an array of the variables
% This could be an arbitrary number of variables
% Here, I declare it as a random vector of 6 variables
LP = rand(1, 6);
% Initialize the result array with zeros
Lc = zeros(size(LP));
% Since Lc1 = LP1, set Lc(1) to the first value in LP(1)
Lc(1) = LP(1);
[rows, cols] = size(LP);
% Loop and set the remaining values
for i=2:cols
% sum(Lc(1:i - 1)) is the sum of the first i - 1 elements in Lc
Lc(i) = LP(i) - sum(Lc(1:i-1));
end
0 个评论
另请参阅
类别
在 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!