How do you write a string in superscript?

14 views (last 30 days)
Kylie Hansen
Kylie Hansen on 13 Mar 2017
Commented: Walter Roberson on 13 Mar 2017
For example, in finding a derivative of a single term, my code is as follows:
function derivative(cons,base,expo)
%Finds the derivative of a single term.
num = expo*cons;
newExpo = expo-1;
deri = strcat(int2str(num),base^{'int2str(newExpo)'})
where I would like the "expo-1" value to be in superscript.
I have also tried:
deri = strcat(int2str(num),base^int2str(newExpo))
deri = strcat(int2str(num),'base^int2str(expo-1)')
deri = strcat(int2str(num),base^'int2str(expo-1)')
I would appreciate a general answer, as well as one specific to this problem, as I will likely need to know how to convert strings to superscript in general for later problems. Thank you in advance!

Answers (1)

Jan
Jan on 13 Mar 2017
Edited: Jan on 13 Mar 2017
deri = strcat(int2str(num), 'base^{', int2str(newExpo), '}')
Or:
deri = sprintf('%dbase^{%d}', num, newExpo)
This is 1 command compared to the 3 commands with strcat and int2str. For scalar inputs I think the sprintf() approaches are always smarter.
  2 Comments
Kylie Hansen
Kylie Hansen on 13 Mar 2017
Is there a way to turn 'base' into a variable instead of a string that is included? For example, if someone calls the function with
derivative(1,x,2)
would it be possible for the input to be '2x^{1}'?
Walter Roberson
Walter Roberson on 13 Mar 2017
bname = inputname(base);
if isempty(bname); bname = 'x'; end %if it was an expression
deri = sprintf('%d%s^{%d}', num, bname, newExpo)

Sign in to comment.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!