1

How to concatenate strings in a loop? For example I have this character array

fruits = char('apple','pear')

I would like to see this output

  apple tart
  pear tart

But when I use this loop:

for f = fruits'
  strcat(f," tart")
end

The output is

ans =

a tart
p tart
p tart
l tart
e tart

ans =

p tart
e tart
a tart
r tart
 tart 

In fact I need this to read a bunch of csv files in a directory. Part of the file name is a variable over which I want to loop over. For example my directory contains the 2 following files from which I want to read data:

peartart.csv
appletart.csv

This other answer using a list of files is nice but then I have no control over the fruit variable name in the file. I wand control over this variable because I will perform a statistical test for each fruit data and store the test result with the fruit name in another file.

Community
  • 1
  • 1
Paul Rougieux
  • 10,289
  • 4
  • 68
  • 110

4 Answers4

3

With fruits = char('apple','pear') you create a natrix of chars. Closest to a list of strings is a cell array.

fruits = {'apple','pear'}

Opening a csv should be something like:

for f = fruits
  csvread([f{:},'tart.csv'])
end

Not sure if the blank before the t is required or not, depends on your file name.

Daniel
  • 36,610
  • 3
  • 36
  • 69
2

This can be done without loops using cellfun if fruits is a cell array:

fruits = {'apple','pear'};
tarts = cellfun(@(x)strcat(x,' tart'),fruits,'UniformOutput',false)

You can then access the strings with tarts{i}:

>> tarts{1}

ans =

apple tart
eigenchris
  • 5,791
  • 2
  • 21
  • 30
  • Thanks but I would like to load a csv file at each loop iteration. Something like data = csvread(char(strcat('apple','tart','.csv'))) – Paul Rougieux Mar 27 '15 at 08:18
1

This is one solution, use a cell array of strings:

fruits={'apple','pear'};
for i_fruit = 1:length(fruits)
  strcat(fruits{i_fruit},' tart')
end
Partha Lal
  • 543
  • 4
  • 16
  • Thank you, however you are using an index `i_fruit` and I would prefer to loop directly over fruit names, as I wrote in a comment on @daniel 's answer. His answer works but I don't manage to use it to open files in a loop so I resort to your solution with indexes. for i_fruit = 1:length(fruits) data = csvread(strcat(fruits{i_fruit},'tart','.csv')); disp(data); end – Paul Rougieux Mar 27 '15 at 09:23
  • Daniel updated his answer and I can now loop directly over the variable name and can use it to open file names in a loop. See accepted answer. – Paul Rougieux Mar 27 '15 at 12:07
0

fruits is a 2D array of size 2x5. When you do

for f=fruits'

you are converting fruits to a 1D column array and looping over each element. You should loop over each row instead, like this:

fruits = char('apple','pear');
for ii=1:size(fruits,1)
   strcat(fruits(i,:),' tart')
end

This outputs:

ans =

apple tart


ans =

pear tart
TyanTowers
  • 160
  • 10