how to select numbers within the required range from one column in the excel
1 view (last 30 days)
Show older comments
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 Comments
Bob Thompson
on 14 Feb 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)
Accepted Answer
Rik
on 14 Feb 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.
More Answers (0)
See Also
Categories
Find more on Spreadsheets in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!