How to extract strings from a table?

1,164 views (last 30 days)
Hi all,
I know this is likely a very basic question, but I can't seem to figure it out. I want to extract strings from a table and put them in their own array. My code is here:
IDs=1718; %Define how many IDS there are in the total table; this was determined from the Excel sheet
masterCountSheet = readtable('Tasks_Count_060118 (streamlined).xlsx'); %Create table containing master count sheet data
for i=1:IDs
However, whenever I reference a specific cell in the table, I get a cell array returned, not a string. Any ideas as to why and how to fix this?
Walter Roberson
Walter Roberson on 2 Oct 2019

Sign in to comment.

Accepted Answer

Guillaume on 2 Oct 2019
Edited: Guillaume on 2 Oct 2019
Why is the size of the array hardcoded (which means the code will break if something change with the file) instead of just asking matlab for it?
In any case, the loop is completely unnecessary:
IDDataArray = masterCountSheet.(1);
IDDataArray = masterCountSheet{:, 1};
IDDataArray = masterCountSheet.NameOf1stVariableInTable;
Note that
returns a table (not a cell array) which consist of just the ith row and first variable of masterCountSheet. To access the content of a table you use {} indexing or . indexing, not ().
Also note that if that first variable indeed contain strings, then initialising the array with zeros is an error. zeros creates a numerical array, not a string array.
  1 Comment
Alex Gimeno
Alex Gimeno on 9 Oct 2019
This worked perfectly -- thank you.

Sign in to comment.

More Answers (1)

Anthony Dave
Anthony Dave on 27 Nov 2020
Edited: Anthony Dave on 27 Nov 2020
@David K and @Walter Roberson's answers enlightened me. You can use the following code in this example.
IDDataArray = string(masterCountSheet{1:IDs,1});
If you just want to read data in all rows, try:
IDDataArray = string(masterCountSheet{:,1});
  1 Comment
Simon Schmidt
Simon Schmidt on 29 Apr 2021
Hi! What if only want the first 3 characters (instead of the whole string) of every row?

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!