Choose certain matrix elements from a matrix
14 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
the cyclist
le 21 Avr 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 commentaire
the cyclist
le 22 Avr 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.
Plus de réponses (2)
James Tursa
le 21 Avr 2015
Modifié(e) : James Tursa
le 21 Avr 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 commentaires
Voir également
Catégories
En savoir plus sur Linear Algebra dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!