Info

この質問は閉じられています。 編集または回答するには再度開いてください。

Writing a for loop to perform an operation on a vector

1 回表示 (過去 30 日間)
Anaya Kharwadkar
Anaya Kharwadkar 2020 年 10 月 5 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
I have a vector x = [4,2,6,5,3,8,2], where n (number of elements) = 7. I want to write a function
f = (1+x1)^n1 + (1+x2)^n2 + (1+x3)^n3 + (1+x4)^n4 + (1+x5)^n5 + (1+x6)^n6.
Please note that I do not want the last element (x7) in this expression. How do I write a for loop for this.
I am new to MATLAB and any help would be appreciated. Thanks!

回答 (1 件)

KSSV
KSSV 2020 年 10 月 5 日
編集済み: KSSV 2020 年 10 月 5 日
Vectorized
x = [4,2,6,5,3,8,2] ;
n = 1:7 ; %[n1 n2 n3 n4 n5 n6 n7] ;
iwant = sum((1+x(1:6)).^n(1:6)) ;
Loop:
x = [4,2,6,5,3,8,2] ;
n = 1:7 ; %[n1 n2 n3 n4 n5 n6 n7] ;
iwant = 0 ;
for i = 1:6
iwant = iwant+(1+x(i))^n(i) ;
end

この質問は閉じられています。

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by