Select 100 random samples from a 50000x9 matrix and perform 50 iterations to save the choices.
3 次查看(过去 30 天)
显示 更早的评论
I have a matrix of size 50000 x 9. I want to select 100 random samples (like a series of 100nos) from different columns in 50 different iterations. Later I want to save the results of these 50 iterations in a matrix. Can someone shed any light?
Thanks
2 个评论
Stephen23
2018-9-25
编辑:Stephen23
2018-9-25
"Later I want to save the results of these 50 iterations in 50 different variables."
Dynamically creating/accessing variable names in a loop is one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug. Read this to know why:
It is simpler and much more efficient to use indexing and one array, just as the MATLAB documentation recommends.
"Can someone shed any light?"
Write a loop and use indexing. What have you tried so far?
采纳的回答
Image Analyst
2018-9-25
Looks like this code should do it:
m = rand(50000, 9);
numIterations = 50;
results = zeros(1, numIterations); % Preallocate results.
for k = 1 : numIterations % 50 iterations
% Get 100 locations randomly.
randomIndexes = randperm(numel(m), 100);
% Extract those locations
selectedValues = m(randomIndexes);
% Do some operation on them, like summing for example.
% Change this to do whatever operation(s) YOU want to do.
results(k) = sum(selectedValues);
end
plot(results, 'b-', 'LineWidth', 2);
grid on;
xlabel('Iteration Number', 'FontSize', fontSize);
ylabel('Result', 'FontSize', fontSize);
caption = sprintf('Results over %d iterations', numIterations);
title(caption, 'FontSize', fontSize);
2 个评论
Image Analyst
2018-9-25
OK, please go ahead and edit. You haven't yet. Be sure to say how many of the 9 columns to you want to randomly select. Let's say you want to select 100 numbers from 4 of the 9 columns. You could use code like this:
rows = 50000;
columns = 9;
m = rand(rows, columns);
numIterations = 50;
columnsToSample = 4;
% Get the columns
cols = sort(randperm(columns, columnsToSample))
results = zeros(numIterations, columnsToSample); % Preallocate results.
for k = 1 : numIterations % 50 iterations
for k2 = 1 : length(cols)
% For each selected column...
thisColumn = cols(k2);
% Get 100 locations randomly.
randomIndexes = randperm(rows, 100);
% Extract those locations
selectedValues = m(randomIndexes, thisColumn);
% Do some operation on them, like summing for example.
% Change this to do whatever operation(s) YOU want to do.
results(k, k2) = sum(selectedValues);
end
end
plot(results, '-', 'LineWidth', 2);
grid on;
xlabel('Iteration Number', 'FontSize', fontSize);
ylabel('Result', 'FontSize', fontSize);
caption = sprintf('Results over %d iterations', numIterations);
title(caption, 'FontSize', fontSize);
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!