0

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?

1
  • 2
    What should the Excel header read when range = cat(2, 2:4, 8, 9:12)? Commented Sep 6, 2013 at 19:31

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

Couldn't you just write :

range = '2:12';

1 Comment

I need the range to be an array for other calculations, and when I change it, I don't want to have to use 2 lines (ex. range = 2:12; rangeChar = '2:12';) because if I change one and forget to change the other my output file will be wrong. Does that make sense?
0

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.