MATLAB Answers

0

How to extract strings from a table?

Asked by Alex Gimeno on 2 Oct 2019
Latest activity Commented on by Alex Gimeno on 9 Oct 2019
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
IDDataArray=zeros(1,IDs)
for i=1:IDs
IDDataArray(i)=masterCountSheet(i,1)
end
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?

  2 Comments

If IDDaraArray at the end is a cell array of strings then you should be able to just do
output = string(IDDataArray)
IDDataArray(i)=masterCountSheet{i,1}

Sign in to comment.

1 Answer

Answer by Guillaume
on 2 Oct 2019
Edited by Guillaume
on 2 Oct 2019
 Accepted Answer

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);
%or
IDDataArray = masterCountSheet{:, 1};
%or
IDDataArray = masterCountSheet.NameOf1stVariableInTable;
Note that
masterCountSheet(i,1)
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

This worked perfectly -- thank you.

Sign in to comment.