フィルターのクリア

if a=[1,2,3,4] how can i get b=[ (1+2),(1+3​),(1+4),(2​+3),(2+4),​(3+4) ] using for loops,Thanks

3 ビュー (過去 30 日間)
MSP
MSP 2016 年 8 月 18 日
編集済み: per isakson 2017 年 1 月 1 日
a=[1,2,3,4]
b=[ (1+2),(1+3),(1+4),(2+3),(2+4),(3+4) ]
  3 件のコメント
MSP
MSP 2016 年 8 月 18 日
編集済み: Fangjun Jiang 2016 年 8 月 18 日
a=[1 2 3 4 ]
b=zeros(1,10)
for i=1:length(a-1)
for(k=2:length(a))
if(i==k)
b=a(k+1)+a(i)
else
b=a(k)+a(i)
end
end
end
MSP
MSP 2016 年 8 月 18 日
the problem im having is how to access (k+1)th element of a and store them in variable b as rowvector

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

採用された回答

James Tursa
James Tursa 2016 年 8 月 18 日
編集済み: James Tursa 2016 年 8 月 18 日
The limits on your first for-loop are not correct. In particular, length(a-1) is not the same as length(a)-1. And the limits on your second for-loop are incorrect as well. You need to start the second loop index at i+1, not hard-coded start at 2. Then, for simplicity, maybe just use a counter to update the appropriate index of b. So, make the following changes:
for i=1:length(a-1)
Make the upper limit length(a)-1 instead of length(a-1)
for(k=2:length(a))
Make the lower limit i+1 instead of 2 (and get rid of the outer parentheses)
if(i==k)
b=a(k+1)+a(i)
else
b=a(k)+a(i)
end
No need for an if-test here. Simply set the appropriate element of b to your sum. E.g.,
x = 0; % <-- Do this at the start of your code
:
x = x + 1; % <-- Increment the subscript counter (inside the inner loop)
b(x) = a(k) + a(i); % <-- Set the appropriate element of b to your sum

その他の回答 (1 件)

Guillaume
Guillaume 2016 年 8 月 18 日
Here's an answer without a loop. More efficient!
a = 1:4
b = sum(nchoosek(a, 2), 2) %use nchoosek(a, 2) to create [1 2; 1 3; 1 4; 2 3; etc.]
  2 件のコメント
MSP
MSP 2016 年 8 月 18 日
Thanks Guillaume.But would u pls provide the crude algorithm using for loops.I would like to clear my confusion regarding looping
J. Webster
J. Webster 2016 年 8 月 18 日
The purpose of homework is to work out things for yourself. Not to go on messageboards and try to get experts to do your work for you.

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

カテゴリ

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