Creating a mxn matrix that is all zeros except for the middle row and middle column which are 1s
45 views (last 30 days)
Show older comments
Hi,
Given an 7x5 matrix, i am to return a mxn matrix M that is all zeros except for the middle row and middle column, which should be all 1s.
I have gotten as far as creating a zeros matrix using the code M=zeros(7,5), but am clueless on how to change the middle row and middle column to 1s.
I should also mention that the code should be a one-liner.
Thank you
0 Comments
Accepted Answer
Wan Ji
on 28 Aug 2021
Edited: Wan Ji
on 28 Aug 2021
M = [0,0,0,1,0,0,0; 0,0,0,1,0,0,0; 1,1,1,1,1,1,1; 0,0,0,1,0,0,0; 0,0,0,1,0,0,0];
Once for all
Or you can do
a = zeros(5,7);
a((1:numel(a))>size(a,1)*(size(a,2)-1)/2&1:numel(a)<=size(a,1)*(size(a,2)+1)/2|mod(1:numel(a),size(a,1))==(size(a,1)+1)/2) = 1
The result is
a =
0 0 0 1 0 0 0
0 0 0 1 0 0 0
1 1 1 1 1 1 1
0 0 0 1 0 0 0
0 0 0 1 0 0 0
We can extend it to any matrix with both odd columns and rows.
a = zeros(9,11);
a((1:numel(a))>size(a,1)*(size(a,2)-1)/2&1:numel(a)<=size(a,1)*(size(a,2)+1)/2|mod(1:numel(a),size(a,1))==(size(a,1)+1)/2) = 1
Then a becomes
a =
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
0 Comments
More Answers (2)
Awais Saeed
on 28 Aug 2021
M = zeros(7,5)
M(:,ceil(size(M,2)/2)) = 1
M(ceil(size(M,1)/2),:) = 1
4 Comments
Awais Saeed
on 28 Aug 2021
This is the shortest code that I can come up with. Why do you need a one line answer? You are not doing it through loops, this is vectorisation which is far better and faster than loops. It is more readable as well.
See Also
Categories
Find more on Creating and Concatenating Matrices 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!