How to use xls in functions?

조회 수: 3 (최근 30일)
KMD
KMD 2017년 11월 23일
댓글: Star Strider 2017년 11월 23일
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
KMD
KMD 2017년 11월 23일
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.

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

답변 (2개)

KSSV
KSSV 2017년 11월 23일
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
KMD
KMD 2017년 11월 23일
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.

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


Star Strider
Star Strider 2017년 11월 23일
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
KMD
KMD 2017년 11월 23일
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 2017년 11월 23일
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.

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

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by