how to sum array

3 ビュー (過去 30 日間)
jeffery lamar
jeffery lamar 2021 年 8 月 6 日
編集済み: Stephen23 2021 年 8 月 6 日
A=[1 4 5 10 9 3 2 6 8 4]
B=[1 7 3 4 1 10 5 4 7 4]
fRow = B+A(1);
sRow = B+A(2);
tRow = B+A(3);
foRow = B+A(4);
fiRow = B+A(5);
siRow = B+A(6);
seRow = B+A(7);
eRow = B+A(8);
nRow = B+A(9);
teRow = B+A(10);
ans = [fRow; sRow; tRow; foRow; fiRow; siRow; seRow; eRow; nRow; teRow]
please i need help with this, how can i write the code to solve the answer if A and B array length is the diffrent from my own array length
Let say A and B will have to be inputted by the user, and the array Length of A and B inputted by the user is less or greater than 10, how will my code solve that.
This is the output
ans =
2 8 4 5 2 11 6 5 8 5
5 11 7 8 5 14 9 8 11 8
6 12 8 9 6 15 10 9 12 9
11 17 13 14 11 20 15 14 17 14
10 16 12 13 10 19 14 13 16 13
4 10 6 7 4 13 8 7 10 7
3 9 5 6 3 12 7 6 9 6
7 13 9 10 7 16 11 10 13 10
9 15 11 12 9 18 13 12 15 12
5 11 7 8 5 14 9 8 11 8
ans =
12

回答 (2 件)

David Hill
David Hill 2021 年 8 月 6 日
  7 件のコメント
DGM
DGM 2021 年 8 月 6 日
編集済み: DGM 2021 年 8 月 6 日
I don't know why you're trying to do this with a loop. For the example you gave, no loops are necessary as we've demonstrated.
This has its own problems:
aLenght = length(A); % this isn't used for anything
C = 1;
while(C <= i) % C is a positive, real integer. it can never be <= sqrt(-1)
u=A(C)+B % this gets overwritten each time
C=C+1;
end
If for some reason (e.g. homework assignment stipulation) you must use a loop, use a for loop instead. If you know the number of iterations beforehand, there's little point dealing with the hazards of a while loop.
Stephen23
Stephen23 2021 年 8 月 6 日
編集済み: Stephen23 2021 年 8 月 6 日
"but the problem now is the output is not in array form, how can make it array fom?"
What exactly is "array form"?
The answers that DGM has shown you are exactly the same as if you do the same calculation in a loop.
Just much simpler.

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


Image Analyst
Image Analyst 2021 年 8 月 6 日
Here is an alternative way using the repmat() function to explicitly turn A and B into 2-D matrices before adding them together:
A=[1 4 5 10 9 3 2 6 8 4]
B=[1 7 3 4 1 10 5 4 7 4]
A2 = repmat(A', 1, length(B))
B2 = repmat(B, length(B), 1)
C = A2 + B2;
It gives the same result as your "ans" and can handle any length of A and B, as long as they're the same of course

カテゴリ

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