Choose certain matrix elements from a matrix
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
the cyclist
2015-4-21
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 个评论
the cyclist
2015-4-22
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.
更多回答(2 个)
James Tursa
2015-4-21
编辑:James Tursa
2015-4-21
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!