How do I create a matrix surrounding the center element?

조회 수: 5 (최근 30일)
J AI
J AI 2019년 11월 4일
편집: Bhaskar R 2019년 11월 4일
I want to create a matrix (n by n, n being odd) that has its central element fixed, and its surrounding elements increasing/decreasing by some constant value. For example:
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.

채택된 답변

Shubham Gupta
Shubham Gupta 2019년 11월 4일
Try:
n = 5;
A = zeros(n);
[r,c] = find(A==0);
sub = [r,c]-(n+1)/2;
for i = 1:(n-1)/2
ind = find((sub(:,1)==-i&sub(:,2)>=-i&sub(:,2)<=i)|(sub(:,1)==i&sub(:,2)>=-i&sub(:,2)<=i)|(sub(:,2)==-i&sub(:,1)>=-i&sub(:,1)<=i)|(sub(:,2)==i&sub(:,1)>=-i&sub(:,1)<=i));
A(ind) = -0.1*i;
end
Let me know if you have doubts !

추가 답변 (1개)

Bhaskar R
Bhaskar R 2019년 11월 4일
편집: Bhaskar R 2019년 11월 4일
% 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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by