how to create for loop in below formula

2 views (last 30 days)
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);

Answers (4)

Ishit
Ishit on 16 Jun 2023
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

Saurabh
Saurabh on 16 Jun 2023
Edited: Saurabh on 16 Jun 2023
% 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

Stephen23
Stephen23 on 16 Jun 2023
Your inefficient approach (with anti-pattern numbered variable names):
LP1 = rand;
LP2 = rand;
LP3 = rand;
LP4 = rand;
LP5 = rand;
LP6 = rand;
Lc1 = LP1
Lc1 = 0.0735
Lc2 = LP2-Lc1
Lc2 = 0.2472
Lc3 = LP3-(Lc1+Lc2)
Lc3 = 0.6106
Lc4 = LP4-(Lc1+Lc2+Lc3)
Lc4 = -0.2612
Lc5 = LP5-(Lc1+Lc2+Lc3+Lc4)
Lc5 = 0.0396
Lc6 = LP6-(Lc1+Lc2+Lc3+Lc4+Lc5)
Lc6 = -0.0814
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)
0.0735 0.2472 0.6106 -0.2612 0.0396 -0.0814
The best approach:
Lc = [LP(1),diff(LP)]
Lc = 1×6
0.0735 0.2472 0.6106 -0.2612 0.0396 -0.0814
Why do you keep deleting and then reposting this exact question? Or were those classmates of yours?

Malay Agarwal
Malay Agarwal on 16 Jun 2023
Edited: Malay Agarwal on 16 Jun 2023
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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!