how to save results in each loop by using for

9 vues (au cours des 30 derniers jours)
Mahdi Torabi
Mahdi Torabi le 8 Mai 2017
Réponse apportée : Arjun le 6 Déc 2024 à 6:10
I am running a program which I need to add white Gaussian noise on signal and filter it. I need to repeat the process for 100 times as I am applying random white Gaussian noise and take median for results, I am using 'for loop' from 1:100 and then need to save results individually for all loops. Could you please let me know that how results could be saved in output? for i = 1:100 - Adding noise - filtering part -Save results (?)
Thanks
  1 commentaire
Adam
Adam le 8 Mai 2017
results = zeros( 100, signalLen ); % Or the reverse, depending what works best for you)
for n = 1:100
results(n,:) = addNoiseAndFilter( mySignal );
end
Storing all results in a 2d matrix is the best approach. It makes the subsequent median trivial. If you want to save the end result to file you can, but it doesn't seem necessary.

Connectez-vous pour commenter.

Réponses (1)

Arjun
Arjun le 6 Déc 2024 à 6:10
I see that you want to save the results generated in different iterations of the "for" loop.
There can be multiple ways in which you can capture the results in between iterations using MATLAB. The choice of the method undertaken can depend on the data being saved. Some of the approaches to save the results are discussed below with demonstration.
  • Using Arrays: You can pre-allocate an array to store the results from each iteration. This is efficient and straightforward.
numIterations = 5;
results = zeros(1, numIterations); % Pre-allocate array for results
for i = 1:numIterations
% Simple operation: square the loop index
results(i) = i^2;
end
disp('Results using Arrays:');
disp(results);
  • Using Cell Arrays: If the results are not scalar and vary in size, you can use a cell array to store them.
numIterations = 5;
results = cell(1, numIterations); % Pre-allocate cell array for results
for i = 1:numIterations
% Simple operation: create an array with squared values
results{i} = (1:i).^2;
end
disp('Results using Cell Arrays:');
disp(results);
  • Using Files: If you want to save the results to a file for each iteration, you can use save to write to a .mat file.
numIterations = 5;
for i = 1:numIterations
% Simple operation: square the loop index
result = i^2;
% Save the result to a file
filename = sprintf('result_%d.mat', i);
save(filename, 'result');
end
disp('Results saved to files: result_1.mat to result_5.mat');
I hope this helps!

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by