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!