Choose certain matrix elements from a matrix
12 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Lucius
el 21 de Abr. de 2015
Respondida: Lucius
el 22 de Abr. de 2015
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;
0 comentarios
Respuesta aceptada
the cyclist
el 21 de Abr. de 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 comentario
the cyclist
el 22 de Abr. de 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.
Más respuestas (2)
James Tursa
el 21 de Abr. de 2015
Editada: James Tursa
el 21 de Abr. de 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));
0 comentarios
Ver también
Categorías
Más información sobre Linear Algebra en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!