0

Trying to read a txt file, then to loop through all string of the txt file. Unfortunately not getting it to work.

fid = fopen(fullfile(source_dir, '1.txt'),'r')
read_current_item_cells = textscan(fid,'%s')
read_current_item = cell2mat(read_current_item_cells);

 for i=1:length(read_current_item)

 current_stock = read_current_item(i,1); 
 current_url = sprintf('http:/www.', current_item)
 .....

I basically try to convert the cell arrays to a matrix as textscan outputs cell arrays. However now I get the message

Error using cell2mat (line 53) Cannot support cell arrays containing cell arrays or objects.

Any help is very much appreciated

user
  • 719
  • 8
  • 17

2 Answers2

3

That is the normal behaviour of textscan. It returns a cell array where each element of it is another cell OR array (depending on the specifier) containing the values corresponding to each format specifier in the format string you have passed to the function. For example, if 1.txt contains

appl 12
msft 23

running your code returns

>> read_current_item_cells
read_current_item_cells = 
    {4x1 cell}

>> read_current_item_cells{1}
ans = 
    'appl'
    '12'
    'msft'
    '23'

which itself is another cell array:

>> iscell(read_current_item_cells{1})
ans =
     1

and its elements can be accessed using

>> read_current_item_cells{1}{1}
ans =
appl

Now if you change the format from '%s' to '%s %d' you get

>> read_current_item_cells
read_current_item_cells = 
    {2x1 cell}    [2x1 int32]

>> read_current_item_cells{1}
ans = 
    'appl'
    'msft'

>> read_current_item_cells{2}
ans =
          12
          23

But the interesting part is that

>> iscell(read_current_item_cells{1})
ans =
     1

>> iscell(read_current_item_cells{2})
ans =
     0

That means the cell element corresponding to %s is turned into a cell array, while the one corresponding to %d is left as an array. Now since I do not know the exact format of the rows in your file, I guess you have one cell array with one element which in turn is another cell array containing all the elements in the table.

Mohsen Nosratinia
  • 9,844
  • 1
  • 27
  • 52
2

What can happen is that the data gets wrapped into a cell array of cell arrays, and to access the stored strings you need to index past the first array with

read_current_item_cells = read_current_item_cells{1};

Converting from cell2mat will not work if your strings are not equal in length, in which case you can use strvcat:

read_current_item = strvcat(read_current_item_cells{:});

Then you should be able to loop through the char array:

for ii=1:size(read_current_item,1)

 current_stock = read_current_item(ii,:); 
 current_url = sprintf('http:/www.', current_stock)
 .....
Buck Thorn
  • 5,024
  • 2
  • 17
  • 27