How can I store the result after each iteration in a row vector?

3 ビュー (過去 30 日間)
Sakshi Koundal
Sakshi Koundal 2021 年 4 月 10 日
コメント済み: Sakshi Koundal 2021 年 4 月 11 日
Below is the sum equation which is of similar form that I need to write in my Objective Function.
I need to write this in my Objective function
I have written the following code using two 'for' loops, it's working fine but the final answer Asum(As) it is storing is only of the last iteration.
Ad = [1 2];
Ac = [1 2 3 4];
for i=1:lenght(Ac)
for j=1:length(Ad)
As=Ad(j)+Ac(i)
end
end
whereas I need the result in the form of a row vector as shown below:
As = [2 3 3 4 4 5 5 6]
Kindly help, thanks
  2 件のコメント
Stephen23
Stephen23 2021 年 4 月 11 日
編集済み: Stephen23 2021 年 4 月 11 日
Using two loops is not a very good use of MATLAB.
Ad = [1,2];
Ac = [1,2,3,4];
C = reshape(Ac+Ad(:),1,[])
C = 1×8
2 3 3 4 4 5 5 6
Sakshi Koundal
Sakshi Koundal 2021 年 4 月 11 日
Thank you Stephen, I'll modify my code.

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

採用された回答

David Fletcher
David Fletcher 2021 年 4 月 10 日
A quick hack would be:
Ad = [1 2];
Ac = [1 2 3 4];
As=[];
for i=1:length(Ac)
for j=1:length(Ad)
As=[As Ad(j)+Ac(i)]
end
end

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by