how to sum array
Mostrar comentarios más antiguos
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
Respuestas (2)
David Hill
el 6 de Ag. de 2021
B'+A;
7 comentarios
jeffery lamar
el 6 de Ag. de 2021
jeffery lamar
el 6 de Ag. de 2021
In R2016b and later, Matlab can do implicit array expansion. By transposing one of the vectors, the result is the sum of a row vector and a column vector -- a 2D array.
% assuming both A,B are vectors of arbitrary length
A = [1 4 5 10 9 3 2 6 8 4];
B = [1 7 3 4 1 10 5 4 7 4];
C = B + A.'
% what happens if they're different lengths?
A = [1 2 3 4];
B = [1 7 3 4 1 10 5 4 7 4];
C = B + A.'
jeffery lamar
el 6 de Ag. de 2021
David Hill
el 6 de Ag. de 2021
What do you mean array form? It is the matrix that you requested in your question.
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.
"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
el 6 de Ag. de 2021
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
Categorías
Más información sobre Logical en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!