lost_and_found
lost_and_found

Reputation: 47

How do I create a matrix in MATLAB surrounding the center element?

I want to create a matrix (n by n, n being odd) in MATLAB that has its central element fixed, and its surrounding elements increasing/decreasing by some constant value. For example:

enter image description here

where my center element is 0 and the surrounding elements are decrementing by 0.1. I am pretty much blank from where to start exactly. Your time and help is highly appreciated.

Upvotes: 0

Views: 166

Answers (2)

David
David

Reputation: 8459

This alternative seems a bit faster than the for loop.

n = 7; % size
vector = -abs((1-n)/2:(n-1)/2)/10; % entries in middle row/column
x = min(vector,vector.') % final result

Upvotes: 5

Bhaskar
Bhaskar

Reputation: 683

% works for only odd numbers as your requirement
n = 5;       %  matrix size
r = (n-1)/2;  % surrounding rows
x = zeros(n);   % array initialization
c = r-1:-1:0;
% assigning  values
for i = 1:r
    x([1+c(i), end-c(i)], :) = -i/10;
    x(:,[1+c(i), end-c(i)]) = -i/10;
end
x   % final matrix

Upvotes: 0

Related Questions