Search code examples
stringmatlabvariablesxlsread

Does anyone know of a way to use a variable as the filename input into xlsread?


EDIT: I figured out the problem. claim was listed as a cell class. Used cell2mat to convert it to char, and the code worked. Thank you, everybody!

I have a string variable set to a file pathway/location. I would like to use this variable as the input to the xlsread function, but Matlab tells me that xlsread cannot take a variable input. I'm having lots of trouble figuring whether a workaround is even possible. Can someone help me out?

 function C = claimReader()

 inp = csv2struct(['C:\Documents and Settings\nkulczy\My Documents\085 Starry Sky\','Starry_Sky_inputs_vert.csv']);
 inputTitles = [{'Output_Dir'};{'Claimz'};{'Prodz'};{'Fault_Locations'};{'Fault_Type'};{'Primary_Failed_Part'};{'Part_Group'};{'Selected_SEAG'};{'Change_Point'};{'Date_Compile'};{'Minimum_Date'}];

 claim = inp.(cell2mat(inputTitles(2)));  %returns a file path/location string

 C = csv2struct(claim);

 end


 function Out = csv2struct(filename)

 %% read xls file with a single header row

 [~, ~, raw] = xlsread(filename);

 [~ , ~, ext] = fileparts(filename);

 if ~strcmpi(ext, '.csv') %convert non .csv files to .csv, so blanks stay blank
      filename=[pwd,'tempcsv',datestr(now,'yymmddHHMMSSFFF'),'.csv'];
      xlswrite(filename,raw);
      [~ , ~, raw] = xlsread(filename);
      delete(filename);
 end

 if size(raw,1)==11 && size(raw,2)==2 %transpose SS inputs (must      match dimensions of input matrix EXACTLY!!!)
     raw = raw';
 end

 nRow = size(raw,1);
 nCol = size(raw,2);
 header = raw(1,:);
 raw(1,:) = [];

 end

Solution

  • Use the syntax as following and there shouldn't be any problems:

    pathname = 'c:\...\filename.xlsx';
    A = xlsread(pathname);
    

    Edit: regarding your code:

    I can't see where you define filename - you should pass claim (it contains the desired path?) to the xlsread-function. Probably you get a cell with chars. So your input needs to be claim{1}