How can I use meshgrid to isolate the center values of a matrix and change them? So if it is 10x10, I want to change the 2x2 at the center. At 20x20, I want to change the 4x4
조회 수: 2 (최근 30일)
이전 댓글 표시
clc, clear, close all; % clear the command window
size = 10; % set the size for matrix, can be any number
x = zeros(size); % create matrix
for i = 1:size^2 % open loop for all values in matrix
if i == 1 % defines first value
x(i) = 1;
% define fixed points before the points in the middle
elseif i == (size^2 - size+1)
x(i) = 3; % defines the top right corner of any matrix size
elseif i == (size)
x(i) = 7; % defines the bottom left corner of any matrix size
elseif i == (size^2)
x(i) = 5; % defines the bottom right corner of any matrix size
% We can now define the rows after the corners are defined
elseif i >= 1 && i <= size
x(i) = 8; % Defines first column
elseif mod(i,size) == 1
x(i) = 2; % Defines the top row
elseif mod(i,size) == 0
x(i) = 6; % Defines bottom row
elseif i >= (size^2 - size+1) && i <= size^2
x(i) = 4; % Defines the last column
% The following fills in all center values for the matrix
% This is because the remaining values are not predefined
else
x(i) = 9;
end
end
disp(x)
This is what I so far. At n = 10 it should have a 2x2 square in the center of value 10
At n = 20 it should have a 4x4 square in the center of value 10
댓글 수: 0
답변 (1개)
Shubham
2024년 10월 12일
For modifying the centre values of the matrix, you can index them using array positions. For example, In the case of a 6x6 matrix, check out the following:
A = zeros(6);
A(3:4,3:4)=10
You can take hints from the above example and generalise it for your use case.
I hope this would help!
댓글 수: 3
Stephen23
2024년 10월 12일
"How could I code it so that it will work for any size matrix?"
For even values of N:
N = 6;
M = N/2;
A = zeros(N);
A(M:M+1,M:M+1) = 10
Odd values of N are left as an exercise for the reader.
Shubham
2024년 10월 12일
Adding on to Stephen's comment,
For your code to work on a matrix of any size, first understand the pattern you wish to have.
Notice you mentioned that you want:
- for n=10 a matrix of 2x2
- for n=20 a matrix of 4x4
Based on your requirement, do you see if you could generalise this? I hope this would give you some hint.
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!