Clear Filters
Clear Filters

Manipulating Matrix elements based on their index without using a for loop.

4 views (last 30 days)
Can I do simple manipulations on each matrix element based on its index without having to run a for loop?
for example, say I want to take the inscribed circular region of diameter n in an n by n matrix A, and set everything else to zero, I would then do
for i = 1:n
for j = 1:n
if ((i-n/2)^2+(j-n/2)^2>n) A(i,j) = 0; end;
end
end
for large n, this becomes a very high memory problem.
the same thing with a square can be done easily, say the matrix A is some arbitrary size and I want the first m by n matrix, I could just do this
A(1:m,1:n)
I am thinking there is some syntax like
A([logical operation based on index])
I know for just value, this can be done with a logical operator directly on the matrix
A<1
returns all the positions of elements less than 1

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 18 Jun 2015
[jj,ii]=meshgrid(1:n,1:n);
A((ii-n/2).^2+(jj-n/2).^2>n)=0
  1 Comment
Tim
Tim on 18 Jun 2015
This doesn't quite work, I think you meant something like this:
n=100
[jj,ii]=meshgrid(1:n,1:n);
A = (sqrt((ii-n/2).^2 + (jj-n/2).^2)< n/2)*100
image(A)

Sign in to comment.

More Answers (1)

Tim
Tim on 18 Jun 2015
Edited: Tim on 18 Jun 2015
Try this.
clear all;
%We want to inscribe a circle of diameter n on an nxn matrix A.
%More generally we want an index based method for assinging
%values to a matrix without having to run a calculation on each element.
%Presumably we want the circle center in the middle. My plan of attack is
%to generate a list of index pairs first and then assign it to the matrix.
%Matrix row/column and coincidentally circle diameter
n=95;
%For efficiency, instantiate the matrix A
A = zeros(n+1);
%Use a paramterized function to generate the i and j indices to appropriate
%resolution(This will change based on how big n is; higher n, more
%resolution required in this step.)
%We must use linear indexing to assign scattered values so calculate a new
%indices vector which gives a numeric value for the element number of each
%index pair i.e. A(1,1) = 1 and A(n,n) would be like 10,000 for n=100.
%luckily we have the sub2ind function which does this for us.
t=0:.01:2*pi;
idx = sub2ind(size(A), int16((n/2).*sin(t))+n/2, int16((n/2).*cos(t))+n/2);
%assign values to your generated indices in A
A(idx)=100;
%Check your work
image(A);
This method should work for any shape you could parameterize or define in a vector form. See my comment on Azzi's answer for the way to generate a filled in shape.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!