0

Let's take a simple example. I am trying to change my way of thinking to get more matrix oriented.

I have data

epsilonM = [0.001 10*h h 0];
situations = ['i.a)' 'i.a)' 'i.Q' 'ii.:w']; 
hleg = legend(sprintf('%s Epsilon = %d, \n', situations, epsilonM));

I would like to get output

i.a) Epsilon = 0.001
i.a) Epsilon = 10*h,
i.Q Epsilon = h,
i.b) Epsilon = 0,

but I get

enter image description here

I have an intuition that there is a better way to do this - component wise.

How can you achieve the result without use of for loops, only by matrices?

1
  • For a 4 line string manipulation, I would use a loop. Your output is all garbled it's printing the 4 elements of situations, then the next part of your string "Epsilon = ", then the 4 elements of epsilonM. This behavior of s/fprintf is expected, but I've never found a good use for it. Commented Oct 14, 2013 at 21:55

2 Answers 2

3

In this case it's easier with cell arrays:

situations = {'i.a)' 'i.a)' 'i.Q' 'i.b)'};
epsilonM = {'0.001' '10*h' 'h' '0'};
aux = strcat(situations, {' Epsilon = '}, epsilonM);
legend(aux);

Note that the curly braces in {' Epsilon = '} are only necessary to prevent strcat from removing trailing white space (see doc of strcat)

Sign up to request clarification or add additional context in comments.

3 Comments

I use also epsilonM as data source. Is there any possibility of change int2str() there somehow? Or should I have two vars?
@Masi You probably need two vars. You could do num2str on your numeric variable epsilonM, but you would get the numbers converted to strings, never an h as part of the strings
@Masi Now that I think about it: you could divide your numeric vector epsilonM by h. So strcat(num2str(epsilonM(:)/h),'h') could generate the desired string representation of epsilonM. Note that the (:) is necessary to turn epsilonMinto a column vector, as num2str gives one result per row. Finally, use this to concat everything: strcat(situations.', {' Epsilon = '}, strcat(num2str(epsilonM(:)/h),'h'))
2

Check the output of this line:

situations = ['i.a)' 'i.a)' 'i.Q' 'ii.:w'];

This is a single char of size 1 16, not the array you intended. I would recommend to use a cell:

situations = {'i.a)' 'i.a)' 'i.Q' 'ii.:w'};.

Thus:

epsilonM = [0.001 10*h h 0];
situations = {'i.a)' 'i.a)' 'i.Q' 'ii.:w'}; 
hleg = legend(sprintf('%s Epsilon = %d, \n', situations{:}, epsilonM));

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.