Add value to previous value while using a for loop

5 ビュー (過去 30 日間)
Vance Blake
Vance Blake 2020 年 8 月 29 日
コメント済み: stozaki 2020 年 8 月 29 日
Hi I am trying to compute the summation of a series of two values and then dvide them using a for loop and calling a function. The values of i can range from 1 to N and I want to sum them according to this relationship COM(from 1 to N) = [m(1)*x(1)]/m(1)+[m(2)*x(2)]/m(2)+...+[m(N)+x(N)]/m(N) I have posted what I have so far but cant crack how to add the previously calculated value to the new one. Any help would be greatly appreciated!
% Part A
N = 1:1:100;
SizeofN = size(N,2);
for i = 1:SizeofN
m(i) = i^(1.1);
x(i) = i^(2);
CoM_num(i) = m(i)*x(i);
CoM_denom(i) = m(i);
end
for j = 1:SizeofN
CoM_tot(j) = CoM_num(j)/CoM_denom(j);
end

回答 (1 件)

stozaki
stozaki 2020 年 8 月 29 日
Hello Vance,
Try adding the following to your script. COMTOT is the cumulative sum.
COMTOTALL = cumsum(CoM_tot);
COMTOT = COMTOTALL(end);
function : cumsum
Regards,
stozaki
  2 件のコメント
Vance Blake
Vance Blake 2020 年 8 月 29 日
編集済み: Vance Blake 2020 年 8 月 29 日
Hi stozaki, so I would like to calculate the cumulative total of the columns in the row vector specified by the current iteration number. So If im on iteration 3 it would sum the first 3 columns in CoM_tot. I have upgraded my code from when I posted but I can't seem to get the fucntion and function call right to perform that operation. Here is what I have and this is the error i get
Output argument "CoM_totM" (and maybe others) not assigned during call to
M = 10:1:100;
LengthofM = length(M);
for n = M:LengthofM
[CoM_totM] = CenterMassCalc(M(n));
end
function [CoM_totM] = CenterMassCalc(M)
SizeofM = size(M,2);
for k = 10:SizeofM
m(k) = k^(1.1);
x(k) = k^(2);
CoM_num(k) = m(k)*x(k);
CoM_denom(k) = m(k);
CoM_totM(k) = sum(CoM_num(1:k))/sum(CoM_denom(1:k));
end
end
stozaki
stozaki 2020 年 8 月 29 日
Hi Vance,
The cause of the error is that CoM_totM has not been initialized, so an error occurs if the result of the CenterMassCalc function is undefined.
M = 10:1:100;
LengthofM = length(M);
for n = M:LengthofM
[CoM_totM] = CenterMassCalc(M(n));
end
function [CoM_totM] = CenterMassCalc(M)
% initialize
CoM_totM = [];
SizeofM = size(M,2);
for k = 10:SizeofM
m(k) = k^(1.1);
x(k) = k^(2);
CoM_num(k) = m(k)*x(k);
CoM_denom(k) = m(k);
CoM_totM(k) = sum(CoM_num(1:k))/sum(CoM_denom(1:k));
end
end
Even if you initialize CoM_totM, the result will be empty.
Is the processing you want to perform appropriate?
stozaki

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeParametric Spectral Estimation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by