how to select numbers within the required range from one column in the excel

1 vue (au cours des 30 derniers jours)
Tian Tian
Tian Tian le 14 Fév 2018
Commenté : Tian Tian le 15 Fév 2018
Hi everyone, I want to read the data from one column in excel file, and select the data within a certain range. The number of selected data is supposed to save in sheet 2. Here is my code:
sym Na;
Xa=xlsread(excelfilename,'A:A');
for i = 1:nrows
if (Xa > 4154 & Xa <= 103854)
Na=Na+1;
end
end
xlswrite(excelfilename,Na,'Sheet2','B2:B2')
But there is a problem causing the 'Na' to be 0 all the time. Does anyone know the problem with my code? I appreciate your time and help.
  2 commentaires
Bob Thompson
Bob Thompson le 14 Fév 2018
Your if statement is examining the entire array of Xa, rather than the individual rows, which I assume is what you're trying to do. You need to add indexing to your Xa call to examine each row.
if (Xa(i) >4151 && Xa(i) <= 103854)
Tian Tian
Tian Tian le 15 Fév 2018
Thank you Bob Nbob!

Connectez-vous pour commenter.

Réponse acceptée

Rik
Rik le 14 Fév 2018
In addition to the remark Bob made, you can also remove the loop and check the entire row in one go:
Xa=xlsread(excelfilename,'A:A');
Na=sum(Xa > 4154 & Xa <= 103854);
xlswrite(excelfilename,Na,'Sheet2','B2:B2')
PS pre-allocating Na to a sym doesn't make sense if you are just going to add it up and write it as a numeric value. Just pre-allocate to 0 if you're using a loop.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by