dustynrobots
dustynrobots

Reputation: 311

cast an array into a string - MATLAB

I have an array that I want to basically capture as text so I can write it to one cell of an Excel file as a column header. It's a range of subjects, and I'll have some data underneath. So the range is:

range = 2:12;

which creates and array, but I want the Excel file header to just read 2:12. I've tried creating another variable to capture this text in one field, using num2str like this:

rangeChar = num2str(range);

and I get:

rangeChar = 2   3   4   5   6   7   8   9  10  11  12

but they are each separate fields, so when exported to Excel they each take up their own cell. The original range is not always sequential - for example I might have

range = cat(2, 2:4, 8, 9:12);

so I can't just do a

rangeChar = sprintf('%d:%d', range(1), range(end)); 

type of thing either. Any thoughts?

Upvotes: 0

Views: 70

Answers (3)

Avico
Avico

Reputation: 321

Use a cell array to hold "range" and use the following code :

range = {2:4, 8, 9:12};
range_str=repmat({''}, size(range));
for i=1:length(range)
    if length(range{i})==1
    range_str{i}=sprintf('%d', range{i});
    else
    range_str{i}=sprintf('%d:%d', range{i}(1), range{i}(end));
    end
end
range_str

Output :

range_str = 

'2:4'    '8'    '9:12'

Upvotes: 0

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

You can do it the other way around and keep the range in the string and extract the vector from that when you need it:

rangeChar = '2:12';
range = eval(rangeChar);

Upvotes: 1

m_power
m_power

Reputation: 3204

Couldn't you just write :

range = '2:12';

Upvotes: 0

Related Questions