1

I have variable input names that I would like to assign to titles of graphs. E.g 'UKtreasury_returns', 'China_logReturns', 'US_ret' ....

I want to extract simply up until the underscore in each example. They are function arguments, so i have tried:

header = inputname(1);
subject = header(1:'_'-1);
finalTitle = [subject, ' - first three PCs'];

the '-1' is there because I do not want the underscore included in the output.

This didn't work, and I get the rror message: 'index exceeds matrix dimensions'.

How can I dynamically reference the underscores? Any tips how a solution might be extended for other indexing problems I might face in the future?

1
  • try subject = textscan(s,'%s %*[^_]','delimiter','_') Commented Mar 20, 2014 at 15:03

3 Answers 3

1

You can't index a string with constituent characters in MATLAB. When you do:

header(1 : '_' - 1);

MATLAB automatically converts the char '_' into an integer index, kind of like what happens in C. Since the value of this integer exceeds the length of your string, you get the error mentioned.

To achieve what you are trying to do, you can do:

strs = strsplit(header, '_');
subject = strs{1};
Sign up to request clarification or add additional context in comments.

Comments

1

Rather than splitting the string, you can find the occurence of '_' in your string and then take only a substring:

k = strfind(header, '_');
subject = header(1:k(1)-1);

This is much faster than using strsplit This code assumes that there is at least one occurrence of '_' in your string.

Comments

0

EDIT: I didn't see the answer given above by @scai. The concatenation problem below was due to me using normal brackets () and not curly brackets {}.

I have managed to do it myself with the follwing code:

header = inputname(1);
strings = strsplit(header, '_');
subject = strings{1}; 
finalTitle = [subject, ' - first three PCs']';
title(finalTitle);

The problem now, however, it that the title is displayed as a colum vector. I have tried using the transpose both in the position shown and the end of the fourth line of code as well as in the last line on finalTitle.

Any suggestions? Is it possible to transpose a text concatenation?

(I have adjusted the size of the figure, its nothing to do with a limitation there)

1 Comment

try finalTitle = strcat(subject, ' - first three PCs') The issue is that subject is a cell, not a string. You can make subject a string with subject=strings{1} instead of subject=strings(1). This is like pointer usage in C.

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.