How to use for and if statements together?

4 vues (au cours des 30 derniers jours)
aa le 29 Fév 2024
Modifié(e) : aa le 29 Fév 2024
I have this problem in my textbook (MATLAB for Behavioral Scientists by Rosenbaum,Vaughan and Wyble) as I am brand new to MATLAB!
% 5.9.4
% Find out how long it takes your computer to identify values greater
% than the overall mean in a 1000×1000 matrix of random numbers,
% using for and if statements. Also find out how long it takes your
% computer to identify values greater than the overall mean through
% instant if-ing. Because the matrix is large, you will want to suppress
% most other output.
I can't seem to workout how to integrate the 'identify larger than overall mean part' of the loop.

Réponse acceptée

Sudarsanan A K
Sudarsanan A K le 29 Fév 2024
Hi Anosha,
To solve the problem described in your textbook, we need to create a 1000x1000 matrix of random numbers, calculate the overall mean of the matrix, and then identify values greater than this mean using two methods:
  1. Using "for" and "if" statements (which is typically slower).
  2. Using logical indexing (referred to as "instant if-ing" in your book, which is much faster).
We will also measure the time it takes to perform each of these tasks using MATLAB's "tic" and "toc" functions.
Here is how you can do it in MATLAB:
% Create a 1000x1000 matrix of random numbers
M = rand(1000, 1000);
% Calculate the overall mean of the matrix
overallMean = mean(M(:));
% Method 1: Using for and if statements
tic; % Start timer
countForIf = 0; % Initialize counter for values greater than mean
for i = 1:numel(M)
if M(i) > overallMean
countForIf = countForIf + 1; % Increment counter
timeForIf = toc; % Measure elapsed time
% Display the time taken using for and if statements
fprintf('Time taken using for and if statements: %.6f seconds\n', timeForIf);
Time taken using for and if statements: 0.033591 seconds
% Method 2: Using logical indexing (instant if-ing)
tic; % Start timer
countLogical = sum(M(:) > overallMean); % Count values greater than mean
timeLogical = toc; % Measure elapsed time
% Display the time taken using logical indexing
fprintf('Time taken using logical indexing: %.6f seconds\n', timeLogical);
Time taken using logical indexing: 0.004527 seconds
In this script, we:
  • Generate a 1000x1000 matrix "M" filled with random numbers using "rand".
  • Compute the overall mean of "M" by using the "mean" function.
  • Count the number of elements exceeding the mean with a "for" loop and "if" statements, and record the duration with "tic" and "toc" functions.
  • Perform the same count more efficiently using logical indexing, and measure the time taken.
  • Output the elapsed time for both methods.
For additional information on the "tic" and "toc" functions, refer these documentations:
I hope this helps!
  1 commentaire
aa le 29 Fév 2024
I had been forgetting to integrate the 'countForIf' line so that is where I was going wrong. Thank you for this step by step tutorial, greatly appreciated as I can see the exact and logical steps.

Connectez-vous pour commenter.

Plus de réponses (2)

Noah Prisament
Noah Prisament le 29 Fév 2024
So right now you are trying to solve "identify values greater than the overall mean."
To break up that part of the problem a bit more, lets think about how you would do that as a human. You would start by calculating the mean and then you would compare values against this mean in order to determine if they were greater.
Lets break this up a bit further into steps:
  1. Calculate the mean of the matrix values
  2. Iterate through each value in the matrix
  3. Compare the value at each iteration to the pre-calculated mean
  4. Do something with the result of this comparison
Steps 1 and 4 can be broken up a bit further, but I will leave that to you to figure out. Also, I'm not sure if you have been taught it yet, but there is some in-built functionality in MATLAB that could assist with step 1 without requiring further breaking it down.
I hope this helps clarify how to approach this problem and gives some insight into future programming problem solving. Remember that you can always think through how you would do something manually and what the steps would be to perform that solution.

John D'Errico
John D'Errico le 29 Fév 2024
Modifié(e) : John D'Errico le 29 Fév 2024
Can you compute the overall mean? Surely you know how to use the function mean. If not, can you compute the overall mean? How would you do that? (MAKE AN EFFORT. Show some effort, and you will get better help.)
Next, can you compare a number to the overall mean? Can you use an if statement? Can you compare the entire matrix to the overall mean?
Being new to MATLAB does not mean you can just give up.


En savoir plus sur Matrix Indexing dans Help Center et File Exchange




Community Treasure Hunt

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

Start Hunting!

Translated by