【发布时间】:2015-05-13 14:06:40
【问题描述】:
所以我需要生成一个由 x 和 y 点组成的矩阵,前提是它们满足在这些 (x,y) 点处的浓度大于 10 的条件。请注意,我首先运行一个代码,让我在每个位置都集中注意力,现在我需要 Matlab 在上述条件下“随机”选择 (x,y) 点。
如果您有任何关于如何解决此问题的建议,我们将不胜感激。
【问题讨论】:
所以我需要生成一个由 x 和 y 点组成的矩阵,前提是它们满足在这些 (x,y) 点处的浓度大于 10 的条件。请注意,我首先运行一个代码,让我在每个位置都集中注意力,现在我需要 Matlab 在上述条件下“随机”选择 (x,y) 点。
如果您有任何关于如何解决此问题的建议,我们将不胜感激。
【问题讨论】:
假设您的数据看起来像这样:
data= [... x y concentration
1, 1, 1; ...
2, 1, 11; ...
1, 2, 12; ...
2, 2, 1 ...
]
您可以找到所有大于 10 的浓度:
data_cbigger10=data(data(:,3)>10,:) % using logical indexing
并从那里选择一个随机点:
randomPoint=data_cbigger10(ceil(size(data_cbigger10,2)*rand),:) % pick a random index
如果尺寸如下:
concentration 的维度是 52x61x61,因为浓度是 c(x,y,time),x 的维度是 1x61,y 的维度是 1x52。 @PetrH – s2015
这应该可以解决问题:
这是你的数据,我只是编造的:
x=linspace(0,1,61);
y=linspace(0,1,52);
con=20*rand(61,52);
现在我发现 con 中所有大于 10 的位置。这会产生一个逻辑矩阵。通过将它与相同大小的随机矩阵相乘,我得到一个具有随机值的矩阵,其中“con”大于 10,但其他任何地方都等于零。
data_cbigger10=rand(size(con)).*(con>10);
通过找到最大值或最小值,选择一个随机点:
for n=1:1:10
data_cbigger10=rand(size(con)).*(con>10);
[vals,xind]=max(data_cbigger10);
xind=squeeze(xind);
[vals,yind]=max(squeeze(vals));
[~,time_ind]=max(squeeze(vals));
yind=yind(time_ind);
xind=xind(yind,time_ind);
x_res(n)=x(xind)
y_res(n)=y(yind)
time_res(n)=time(time_ind)
con_res(n)=con(xind,yind,time_ind)
con(xind,yind,time_ind)=0; % setting the choosen point to zero, so it will not be choosen again.
end
希望现在对你有用。
【讨论】:
假设您将每个点 (x,y) 的浓度存储在数组 concentration 中,您可以像这样使用 find() 和 randsample() 函数:
conGT10 = find(concentration>10); % find where concentration is greater than 10 (gives you indices)
randomPoints = randsample(conGT10,nn); % choose nn random numbers from those that satisfy the condition
x1 = x(randomPoints); % given the randomly drawn indices pull the corresponding numbers for x and y
y1 = y(randomPoints);
编辑:
以上假设数组x、y 和concentration 是1d 并且长度相同。显然,这不适用于您的问题。
您在(x,y) 平面上有一个点网格,并且您在不同时间段测量此网格上的集中度。所以x的长度是nx,y的长度是ny,concentration的大小是nxnynt。为简单起见,我假设您只测量一次浓度,即 nt=1 和浓度只有 2d 数组。
我之前的答案的修改版本如下:
[rows,cols] = find(concentration>10); % find where concentration is greater than 10 (gives you indices)
randomIndices = randsample(length(rows),nn); % choose nn random integers from 1 to n, where n is the number of observations that satisfy the condition 'concentration>10'
randomX = x(rows(randomIndices));
randomY = y(cols(randomIndices));
【讨论】:
x、y 和concentration 是相同长度的一维数组。如果不是,那么我可能无法完全理解您的工作。