Adding a single number to an entire matrix
Show older comments
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
b = [1,2,3;4,5,6;7,8,9]
c = a + b
Use square brackets [] to code vectors and matrices.
5 Comments
David Ebert
on 3 Feb 2023
in R2022b implicit expansion seems to not be included anymore unfortunately... :(
John D'Errico
on 3 Feb 2023
Edited: John D'Errico
on 3 Feb 2023
@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
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..
David Ebert
on 4 Feb 2023
@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
Walter Roberson
on 4 Feb 2023
What is
size(s_combined_projected_tc_and_predicted_sw)
size(s_get_projected_MMSL)
at the time of the problem?
David Ebert
on 4 Feb 2023
Edited: David Ebert
on 4 Feb 2023
Oh, I have made a mistake. I'm sorry. One of the values was not found, giving an empty vector, no wonder.
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!