if we enter n rows and m colums and gets the output of 2n rows and 2m columns
이전 댓글 표시
Write a function named blocks that takes two positive integers, n and m, as input arguments (the function does not have to check the format of the input) and returns one matrix as an output argument. The function needs to return a 2n-by-2m matrix where the upper right and lower left n-by m sub matrices are all zeros and the rest of the matrix are all ones.
채택된 답변
추가 답변 (4개)
Patricio Mosquera
2016년 8월 26일
이동: DGM
2024년 1월 1일
Just choose your n and m
A = [1 0 ; 0 1];
B = ones([n, m]);
out = kron(A,B);
ANAMIKA YADAV
2019년 10월 15일
function out=blocks(n,m);
out=zeros([n m]*2);
out(3:4,1:3)=1;
out(1:2,4:6)=1;
댓글 수: 1
Himanshu Gabhane
2020년 6월 4일
function out=blocks(n,m)
out=zeros([n m]*2);
out(end/2+1:end,1:end/2)=1;
out(1:end/2,end/2+1:end)=1;
end
댓글 수: 1
While this at least calculates the output based on the input parameters (unlike @ANAMIKA YADAV's answer), the result is still completely inverted.
SWAPAN KUMAR
2023년 3월 9일
편집: DGM
2024년 1월 1일
function result = blocks(n,m)
% create a matrix of ones of size n x m
ones_matrix =ones([n,m]);
% create a matrix of zeros of size n x m
zeros_matrix = zeros([n,m]);
% create a matrix of ones of size n x m and concatenate it with a matrix of zeros of size n x m
top_row = [ones_matrix zeros_matrix];
% create a matrix of zeros of size n x m and concatenate it with a matrix of ones of size n x m
bottom_row = [zeros_matrix ones_matrix];
% concatenate the top row and bottom row vertically to create a 2n x m matrix
matrix_first_half = [top_row; bottom_row];
% concatenate the bottom row and top row vertically to create a 2n x m matrix
matrix_second_half = [bottom_row; top_row];
% concatenate the first half and second half horizontally to create a 2n x 2m matrix
result = [matrix_first_half matrix_second_half];
end
댓글 수: 1
DGM
2024년 1월 1일
This creates the correct result, then it duplicates it and concatenates again, so the output is twice as wide as it should be. Why all the extra baloney that wasn't even part of the assignment? Just delete the unnecessary stuff and you're back to a correct result.
function result = blocks(n,m) % n,m are backwards by requirement
% create a matrix of ones of size n x m
ones_matrix =ones([n,m]);
% create a matrix of zeros of size n x m
zeros_matrix = zeros([n,m]);
% create a matrix of ones of size n x m and concatenate it with a matrix of zeros of size n x m
top_row = [ones_matrix zeros_matrix];
% create a matrix of zeros of size n x m and concatenate it with a matrix of ones of size n x m
bottom_row = [zeros_matrix ones_matrix];
% concatenate the top row and bottom row vertically to create a 2n x m matrix
result = [top_row; bottom_row];
end
카테고리
도움말 센터 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!