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

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);

답변 (1개)

Joseph Cheng
Joseph Cheng 2014년 7월 17일
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

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.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Data Import from MATLAB에 대해 자세히 알아보기

질문:

2014년 7월 17일

댓글:

2014년 7월 17일

Community Treasure Hunt

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

Start Hunting!

Translated by