Reputation: 2874
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?
Upvotes: 1
Views: 1279
Reputation: 300
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.
Upvotes: 1
Reputation: 2874
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)
Upvotes: 0
Reputation: 3876
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};
Upvotes: 1