Adding a single number to an entire matrix

How do you add a single number to each element within a matrix?
i.e.
a = 5
b = (1,2,3;4,5,6;7,8,9)
c = a + b

Answers (1)

Exactly as you wrote it!
a = 5
a = 5
b = [1,2,3;4,5,6;7,8,9]
b = 3×3
1 2 3 4 5 6 7 8 9
c = a + b
c = 3×3
6 7 8 9 10 11 12 13 14
Use square brackets [] to code vectors and matrices.

5 Comments

in R2022b implicit expansion seems to not be included anymore unfortunately... :(
@David Ebert Really? You would, of course, be completely wrong. Do you honestly think they would just remove a major feature of the language, something present since MATLAB was first written. That would completely disable every piece of code ever written, millions of lines of code.
a = 5;
b = [1,2,3;4,5,6;7,8,9];
c = a + b
c = 3×3
6 7 8 9 10 11 12 13 14
Implicit expansion of scalars is still included as a part of MATLAB syntax, as it always has been. If you think it has been removed, then show where you think it was removed as a fresh question, and we can explain why that is incorrect..
@John D'Errico Thanks for getting back to me so quickly! I am trying to simply add one constant to all values within an array, however the error message keeps coming back as:
Error using +
Arrays have incompatible sizes for this operation.
Even with bsxfun as seen below:
s_calculate_total_projected_sl = bsxfun(@plus, s_combined_projected_tc_and_predicted_sw, s_get_projected_MMSL);
An error message comes back as:
Error using bsxfun
Non-singleton dimensions of the two input arrays must match each other.
In version R2021b this was always not an issue, and worked fine. I would appreciate any insight into this.
Thanks!
Best,
David
What is
size(s_combined_projected_tc_and_predicted_sw)
size(s_get_projected_MMSL)
at the time of the problem?
Oh, I have made a mistake. I'm sorry. One of the values was not found, giving an empty vector, no wonder.

Sign in to comment.

Asked:

on 13 May 2021

Edited:

on 4 Feb 2023

Community Treasure Hunt

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

Start Hunting!