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!