Only first column variable gets read when generating function, Why.

6 views (last 30 days)
it might be a basic question. I am a beginner.
When I am trying to import an excel file with 5 columns and row 1 as column header, and generating a function for doing the same, MATLAB is not generating 5 variable as per the column headers, but only one variable and that too with the default name, ans.
Kindly help.
Here is the code:
function [Date,Open,High,Low,Close] = importfile(workbookFile,sheetName,startRow,endRow)
% If no sheet is specified, read first sheet
if nargin == 1 || isempty(sheetName)
sheetName = 1;
end
% If row start and end points are not specified, define defaults
if nargin <= 3
startRow = 2;
endRow = 250;
end
%%Import the data, extracting spreadsheet dates in MATLAB serial date number format (datenum)
[~, ~, raw, dateNums] = xlsread(workbookFile, sheetName, sprintf('A%d:E%d',startRow(1),endRow(1)),'' , @convertSpreadsheetDates);
for block=2:length(startRow)
[~, ~, tmpRawBlock,tmpDateNumBlock] = xlsread(workbookFile, sheetName, sprintf('A%d:E%d',startRow(block),endRow(block)),'' , @convertSpreadsheetDates);
raw = [raw;tmpRawBlock]; %#ok<AGROW>
dateNums = [dateNums;tmpDateNumBlock]; %#ok<AGROW>
end
%%Replace date strings by MATLAB serial date numbers (datenum)
R = ~cellfun(@isequalwithequalnans,dateNums,raw) & cellfun('isclass',raw,'char'); % Find spreadsheet dates
raw(R) = dateNums(R);
%%Create output variable
data = reshape([raw{:}],size(raw));
%%Allocate imported array to column variable names
Date = data(:,1);
Open = data(:,2);
High = data(:,3);
Low = data(:,4);
Close = data(:,5);

Answers (1)

Joseph Cheng
Joseph Cheng on 17 Jul 2014
Cursory look at the code shows no problems but it maybe how you are calling the function. How are you running the function?
if you go:
importfile(workbookFile,sheetName,startRow,endRow)
It won't generate the 5 variables by itself. you need to go
[Date,Open,High,Low,Close] = importfile(workbookFile,sheetName,startRow,endRow)
to assign the 5 outputs of importfile to something.
  1 Comment
Joseph Cheng
Joseph Cheng on 17 Jul 2014
Example
if i create a function
function [x y z]=testfunction(x,y,z)
x = 2*x;
y=3*y;
z = z/z;
and run it by typing
testfunction(1,2,3)
i'll get the output of ans = 2
or if i go
[A B]=testfunction(1,2,3);
A will be = 2 and B=6, with no entry for the 3rd output.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!