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

Torsten
Torsten 2017년 5월 8일
What result do you expect from your "a+b" operation ?
Best wishes
Torsten.
I want to add m to each row of A result should be
3 5 7
4 6 8
5 7 9
Torsten
Torsten 2017년 5월 8일
편집: Torsten 2017년 5월 8일
m must be a column vector:
m = [2;4;6]
Best wishes
Torsten.
Steven Lord
Steven Lord 2017년 5월 8일
This behavior is known as implicit expansion and was added to the arithmetic operators like + in release R2016b.

댓글을 달려면 로그인하십시오.

 채택된 답변

KL
KL 2017년 5월 8일

0 개 추천

For the "edited" question,
A =[1 1 1
2 2 2
3 3 3]
m =[2 4 6]
c = bsxfun(@plus,A,repmat(m,3,1))

댓글 수: 3

Maryada Maryada
Maryada Maryada 2017년 5월 8일
Thanks a lot
Jan
Jan 2017년 5월 8일
@KL: If you use bsxfun, you can omit the repmat.
KL
KL 2017년 5월 8일
oh yes, that's right, thanks Jan!

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Jan
Jan 2017년 5월 8일
편집: Jan 2017년 5월 8일

1 개 추천

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)
KL
KL 2017년 5월 8일

0 개 추천

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

I want to add m to each row of A result should be
3 5 7
4 6 8
5 7 9

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

질문:

2017년 5월 8일

댓글:

2017년 5월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by