Emma
Emma

Reputation: 618

combining string and number in matlab

Say that I had a matrix of temperature values and a vector corresponding to the depth of the measurements, e.g.

depth = [1,4,8,11,15,16,20];
Temp = rand(1800,7);

I would like to insert a row of headings into the first row of Temp, where each heading represents the depth of the measurement. I need the heading to state temp and then the depth e.g. temp1, temp4, temp8, temp11... etc.

I was thinking of doing something like defining 'temp' and then adding the corresponding depth of each column, e.g.

varstarter = 'temp';

And then use something like 'regexp' but I'm not sure on how this would work. Any suggestions?

Upvotes: 2

Views: 2198

Answers (2)

Andrey Rubshtein
Andrey Rubshtein

Reputation: 20915

Small improvement of style over the good answer of @arne.b:

 arrayfun(@(x) {['temp' int2str(x)]},depth);

Check out this post for more details.

Upvotes: 3

arne.b
arne.b

Reputation: 4340

arrayfun(@(x) ['temp' int2str(x)],depth,'UniformOutput',false)

Here, @(x) ['temp' int2str(x)] defines an anonymous function that appends an integer input as characters to the given character sequence temp. arrayfun then applies this function to every element of the second argument, i.e. depth. (Since arrayfun is most often used to produce numerical output, e.g. one number per application of the function, the output usually is a matrix with size in at least one dimension equal to the second input. The 'UniformOutput',false option thus tells it that this is not the case here (the length of the strings depends on the number of digits of each input), the output needs to be a cell array.)

Use [ans; num2cell(Temp)]; to combine headings and numerical data into one cell array.

Upvotes: 5

Related Questions