Choose certain matrix elements from a matrix

4 views (last 30 days)
I have an NxN matrix and define a circle of a certain radius. All encircled matrix elements are 1 and the rest 0. Afterwards, I want to apply some multiplication only for the 1s. In order to fasten the process how do I select only the 1s and not the 0s?
N = 2^10;
R = 0.001225;
xmax = 3*R;
x = linspace(-xmax,xmax,N);
y = x;
[xg,yg] = ndgrid(x,y);
Efield_x = zeros(N);
r = sqrt(xg.^2 + yg.^2);
Efield_x(r < R) = 1;
%NumberOfOnes = sum(Efield_x(:) == 1);
phase = exp(1i * (rand(N)*0.5*pi-0.25*pi));
Efield_x = Efield_x .* phase;
In the end I take every matrix element and calculate a random value for each. Especially for larger matrices it would be much faster if we could only calculate with the 1-matrix elements. For this only as many random number need to be created as there are number of 1s. So instead of rand(N) there should be rand(NumberOfOnes) in the second last line. But how to apply this to the 1-matrix elements? Something like this?
Efield_x = Efield_x(r<R) .* phase;

Accepted Answer

the cyclist
the cyclist on 21 Apr 2015
Here is one way:
N = 2^10;
R = 0.001225;
xmax = 3*R;
x = linspace(-xmax,xmax,N);
y = x;
[xg,yg] = ndgrid(x,y);
Efield_x = zeros(N);
r = sqrt(xg.^2 + yg.^2);
isWithinCircle = r<R;
Efield_x(isWithinCircle) = 1;
%NumberOfOnes = sum(Efield_x(:) == 1);
phase = exp(1i * (rand(nnz(isWithinCircle),1)*0.5*pi-0.25*pi));
Efield_x(isWithinCircle) = Efield_x(isWithinCircle) .* phase;
  1 Comment
the cyclist
the cyclist on 22 Apr 2015
The variable isWithinCircle is a logical array that is true when r<R and false when r>=R.
You could define a variable
isOutsideCircle = not(isWithinCircle)
(This actually includes points strictly on the circle, too.)
You could then do operations on
Efield_x(isOutsideCircle)
in similar way.

Sign in to comment.

More Answers (2)

James Tursa
James Tursa on 21 Apr 2015
Edited: James Tursa on 21 Apr 2015
You could use logical indexing for this. E.g.,
z = r < R; % Logical result for 1's locations
z = z(:); % Turn into column vector
k = sum(z); % Number of 1's
Efield_x(z) = Efield_x(z) .* exp(1i * (rand(k,1)*0.5*pi-0.25*pi));

Lucius
Lucius on 22 Apr 2015
What would be the subsequent code-line if one wants to apply an operation to the Efield_x(isWithinCircle) plus the matrix elements that are outside the circle with radius R?

Products

Community Treasure Hunt

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

Start Hunting!