Using the matlab to achieve the a(k)+a(j) when k is not equal to j in every stage

1 回表示 (過去 30 日間)
i want to write a code which is a(k)+a(j), but k can't be equal to j,then sum it every stage ,i mean
  1. when k=1,sumj=a(k)+a(j)=a(1)+a(2)=3, sumj=a(k)+a(j)=a(1)+a(3)=4, sumj=a(k)+a(j)=a(1)+a(4)=5,b=3+4+5=12
  2. when k=2 ,sumj=3,sumj=5,sumj=6,b=3+5+6=14
  3. when k=3 ,sumj=4,sumj=5,sumj=7,b=4+5+7=16
  4. when k=4 ,sumj=5,sumj=6,sumj=7,b=5+6+7=18
a=[1 2 3 4]
sumj=0;
b=0;
for k=1:4
for j=1:4
if j~=k
sumj = a(k)+ a(j)
end
end
b=b+sumj
end
but this code will show
> sumj=3,sumj=5,sumj=6,b=5+6=11 (b shouldn't be 11,it should be 14)
> sumj=4,sumj=5,sumj=7,b=5+6+7=18 (b shouldn't be 18,it should be 16)
> sumj=5,sumj=6,sumj=7,b=5+6+7+7=25 (b shouldn't be 25,it should be 18)
How do i modify the code to let the result become what i want?

採用された回答

Stephen23
Stephen23 2019 年 2 月 11 日
編集済み: Stephen23 2019 年 2 月 11 日
a = [1,2,3,4];
for k = 1:4
b = 0;
for j = 1:4
if j~=k
b = b + a(k) + a(j);
end
end
disp(b)
end
Displays:
b = 12
b = 14
b = 16
b = 18
Note that no loop is required:
>> [X,Y] = ndgrid(1:4);
>> Z = ~eye(4);
>> V = sum(a(X).*Z+a(Y).*Z,1)
V =
12 14 16 18
  2 件のコメント
yang-En Hsiao
yang-En Hsiao 2019 年 2 月 11 日
About the first method you said,if i want to plus 1 to all b,that is ,the b answer will become
b=12+1=13
b=14+1=15
b=16+1=17
b=18+1=19
How do i rewrite the code? because i found that i can't just rewrite like this
c=disp(b)+1
the window will tell me that
Error using disp
Too many output arguments
Stephen23
Stephen23 2019 年 2 月 11 日
disp(b+1)

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGraphics Object Programming についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by