how to create for loop in below formula
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (4)
Ishit
el 16 de Jun. de 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
0 comentarios
Saurabh
el 16 de Jun. de 2023
Editada: Saurabh
el 16 de Jun. de 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
0 comentarios
Stephen23
el 16 de Jun. de 2023
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 comentarios
Malay Agarwal
el 16 de Jun. de 2023
Editada: Malay Agarwal
el 16 de Jun. de 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
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!