how to create for loop in below formula
조회 수: 2 (최근 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!