Matrix basic operation error
Mostrar comentarios más antiguos
I have following code A =
1 1 1
2 2 2
3 3 3
m =
2 4 6
and I am calculating A + m
And I am getting error
Error using + Matrix dimensions must agree
What is wrong in my code.
4 comentarios
Torsten
el 8 de Mayo de 2017
What result do you expect from your "a+b" operation ?
Best wishes
Torsten.
Maryada Maryada
el 8 de Mayo de 2017
m must be a column vector:
m = [2;4;6]
Best wishes
Torsten.
Steven Lord
el 8 de Mayo de 2017
This behavior is known as implicit expansion and was added to the arithmetic operators like + in release R2016b.
Respuesta aceptada
Más respuestas (2)
In modern (>= 2016b) Matlab versions use:
A = [1 1 1; ...
2 2 2; ...
3 3 3];
m = [2 4 6];
A + m
For older Matlab versions:
bsxfun(@plus, A, m)
1 comentario
Maryada Maryada
el 8 de Mayo de 2017
KL
el 8 de Mayo de 2017
If you enter your code on your command window,
>> a = [1 2 3 4]
b = [5; 6; 7]
you would see
a =
1 2 3 4
b =
5
6
7
which mean 'a' has 1 row and 4 columns and 'b' has 1 column and 3 rows. Basically if you want to add two matrices, they should be of same size so you can add the corresponding elements to produce a resultant matrix of the same dimension. For example,
a = [1 2 3]
b = [5 6 7]
here, this gives you
a =
1 2 3
b =
5 6 7
both 'a' and 'b' have 1 row and 3 columns. If you add them like you did in your question
>> c = a+b
then you will get
c =
6 8 10
each value of 'c' is simply the sum of corresponding elements in 'a' and 'b'. If you want to do matrix multiplication, it's a little more complicated so I'd suggest you ask another question or simply have a read here .
1 comentario
Maryada Maryada
el 8 de Mayo de 2017
Categorías
Más información sobre Creating and Concatenating Matrices 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!