Search code examples
excelmatlabrangexlsread

Secifying a common range for xlsread function in Matlab


I am trying to figure out how to specify a common range for xlsread() function in matlab.

Usually I use n=xlsread('filename','#sheet','A1:A10'), but I have quite a bit of data in the same sheet and I'd like to know if I can specify it with one range, i.e . if all my data is between '1:10', I want to specify 1:10 as range, and only call the letter values of each column.

I was thinking to do it as follows:

function [a,b,c]=getdata(filename,'1:10')
a=xlsread(filename,1,'A:A'???)
b=xlsread(filename,1,'B:B'???)
c=xlsread(filename,1,'C:C'???)
end

After some research I could not find any information as to how this is done.

Thanks in advance,

Greg


Solution

  • If you want to read 1 to 10 rows of column A, use:

    data = xlsread(filename, 1, 'A1:A10');
    

    If you want to read 1 to 10 rows of all columns, use:

    data = xlsread(filename, 1, '1:10');
    

    If you want to read 1 to 10 rows of, say, first three columns A, B, and C, use:

    data = xlsread(filename, 1, 'A1:C10'); 
    

    Using dynamic variable names is always a bad idea. Read this for explanation. But if you still want to create a, b, and c and so on depending on the number of columns in the Excel file, you can use:

    for k=1:size(data,2)
       assignin('caller', char(96+k), data(:,k));  %or char(64+k) for block letters
    end
    

    The above will work if number of columns are less than or equal to 26. This may only be feasible if you're dealing with a few columns. But I still recommend to avoid it.