How to store values in summation for loop?

2 ビュー (過去 30 日間)
Kai Hii
Kai Hii 2022 年 6 月 9 日
編集済み: Kai Hii 2022 年 6 月 10 日
Hi, i dont know how to store values for each iteration? It keeps showing up as the same values for example iteration 1 =[50 50 50], iteration 2=[100 100 100]
  2 件のコメント
KSSV
KSSV 2022 年 6 月 9 日
Copy and paste your code here.....Image nippet will not help.
John D'Errico
John D'Errico 2022 年 6 月 9 日
A picutre of your code does nothing, because we cannot use that code. Just paste in the code as text. Why do you want to make it more difficult to get help?

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

回答 (2 件)

Sajid Afaque
Sajid Afaque 2022 年 6 月 9 日
編集済み: Sajid Afaque 2022 年 6 月 9 日
you need to create an array to store your results,
currently with this approach you are over-writing your results in variable s after each iteration
and also here s is an array of zeros and you are adding scalar to entire array in each iteration,
so finally you will have results obtained in final iteration and all the values would be equal
k=1:5;
s=zeros(1,length(k));
store_values = []; %create a where where you need to store results
for i= length(k)
store_value{i}=s(i)+(((-1).^k(i)).*(k(i).^(k(i)+1)))/(2.^k(i)) %focus on left side of equate, modify the right side of the equation as you need
end
%try this should work

John D'Errico
John D'Errico 2022 年 6 月 9 日
編集済み: John D'Errico 2022 年 6 月 9 日
You understand how to index a variable, thus k(i). But when you write this:
s = s + (stuff)
It increments ALL elements of the vector s.
Is there a good reason why you did not try:
s(i) = s(i) + (stuff)
inside the loop?
For example, if I write this:
X = [2 3 5];
Y = X + 2
Y =
4 5 7
do you see that it adds 2 to every element of X? However, if I write this:
X(1) = X(1) + 2
X =
4 3 5
then it impacts only one element of X.
  1 件のコメント
Kai Hii
Kai Hii 2022 年 6 月 10 日
編集済み: Kai Hii 2022 年 6 月 10 日
Yeah I tried doing it this way but it's not adding to itself.
For example, if i have a summation equation (2.^x), iteration 1 should be 2.0, iteration 2 should be (2.0+4.0) and iteration 3 should be (2.0+4.0+8.0) but what it's doing is that in the array, iteration 1 is 2.0, iteration 2 is 4.0 and iteration 3 is 8.0

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by