Replacing a part of a matrix in two commands?

2 views (last 30 days)
I was given a sample question for an exercise today. It goes:
Create the following matrix by typing two commands. Do not type individual elements explicitly.
I started by defining E as a 5x5 matrix of zeros.
E = zeros(5)
This was command 1 but I can't figure out how to replace the given part with consecutive numbers in a single command. I thought of using:
E(3:5,3:5) = ...
but I couldn't figure out what to put on the right hand side.

Answers (2)

Matt J
Matt J on 4 Nov 2021
Edited: Matt J on 4 Nov 2021
It's so hard to know what constitutes a "command" in the opinion of your instructor. The following does it in one line,
E(3:5,3:5)=reshape(1:9,3,3).'
E = 5×5
0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 0 0 4 5 6 0 0 7 8 9
Is this a valid solution just because reshape() is the only function call that does not have its own operator? The transpose is not a command? The subsasgn operation is not a command? The colon operation 1:9 is not a command?

Matt J
Matt J on 4 Nov 2021
Maybe as follows?
E(3:5,3:5)=(1:3:7).' + (0:2)
E = 5×5
0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 0 0 4 5 6 0 0 7 8 9

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!