How do you write a string in superscript?

9 次查看(过去 30 天)
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!

回答(1 个)

Jan
Jan 2017-3-13
编辑:Jan 2017-3-13
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 个评论
Kylie Hansen
Kylie Hansen 2017-3-13
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 2017-3-13
bname = inputname(base);
if isempty(bname); bname = 'x'; end %if it was an expression
deri = sprintf('%d%s^{%d}', num, bname, newExpo)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by