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
3 次查看(过去 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!