Paul Rougieux
Paul Rougieux

Reputation: 11399

How to concatenate strings in a loop?

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.

Upvotes: 1

Views: 1795

Answers (4)

Daniel
Daniel

Reputation: 36710

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.

Upvotes: 3

TyanTowers
TyanTowers

Reputation: 160

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

Upvotes: 0

eigenchris
eigenchris

Reputation: 5821

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

Upvotes: 2

Partha Lal
Partha Lal

Reputation: 541

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

Upvotes: 1

Related Questions