How to use xls in functions?

3 views (last 30 days)
KMD
KMD on 23 Nov 2017
Commented: Star Strider on 23 Nov 2017
I am currently working on a project that requires me to load an excel file into MATLAB. I know I can do this by using an xlsread, but whenever I try to do this in a function file it only outputs the numeric values, not the headers with it. I am confused by this because it runs properly as a script, but the project requires me to use an xlsread in a function. I have tried:
function [table, txt] = trails()
[table, txt] = xlsread('trails.xlsx');
I do not understand why this isn't working. The only thing that comes to mind is the headers are strings, but I'm not sure if that is the issue.
  1 Comment
KMD
KMD on 23 Nov 2017
I am finding (in general) I am unable to assign text within functions. For example, if I am looking at names and height, if I were to execute
function [num, txt, raw]=demographic()
[num, txt, raw]=xlsread('demographic_data.xlsx');
end
It only gives me the numerical value of the heights and outputs this to ans. It does not show me what the names are or assign the heights to num.

Sign in to comment.

Answers (2)

KSSV
KSSV on 23 Nov 2017
USe:
[num,txt,raw] = xlsread('my file') ;
num gives only numerical data
txt gives only text data
raw gives whole data of the sheet
  1 Comment
KMD
KMD on 23 Nov 2017
So I tried
function [table, txt, raw]= trails()
[table, txt, raw]= xlsread('trails.xlsx');
end
But this did not fix the issue. My code is able to read and output the table (meaning the numerical values of the trials file, but it still does not output the headers or text. Additionally, when this code is ran the numerical values are output, but they are not assigned to the variable table, instead it is assigned to ans.

Sign in to comment.


Star Strider
Star Strider on 23 Nov 2017
In your code, the headers (and other string information) will be in the ‘txt’ variable. The numeric values will be in the badly-named ‘table’ variable.
You might find using the readtable (link) function (in R2013a and later) to be preferable.
  6 Comments
KMD
KMD on 23 Nov 2017
Right, and when I enter that as a script file it assigns it to num, txt, raw. But when I go to do that in a function file it does not work.
function [num, txt, raw]=demographic()
[num, txt, raw]=xlsread('demographic_data.xlsx');
end
For this output it only assigns it to ans, it does not assign it to num , txt, or raw.
Star Strider
Star Strider on 23 Nov 2017
If you call it as:
[num, txt, raw] = demographic;
the variables will be assigned ‘num’, ‘txt’, and ‘raw’ in the calling script workspace.
If they are assigned as ‘ans’, you are doing something wrong that I cannot guess.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!