how to input a string into a function?
Mostrar comentarios más antiguos
my function is
function [Title,Author,Number_of_pages]=disp_book(Tit,Aut,Nu_of_pg)
fprintf('Title: %s',Tit)
fprintf('Author: %s',Aut)
fprintf('Number of pages: %d',Nu_of_pg)
end
but if i prompt disp_book(name,author,33) the computer doesnt take the string. How do I make it work?
3 comentarios
Jan
el 27 de Abr. de 2017
"the computer doesnt take the string" does not explain exactly, what you want and what you get. The shown function does work exactly in the way it is defined.
What is the contents of the variables "name" and "author"?
Swapnil srivastava
el 27 de Abr. de 2017
Stephen23
el 27 de Abr. de 2017
@Swapnil srivastava: your comment shos that you forgot to use quotation marks to define the string. See my answer for the correct way to call this function with string inputs.
Respuestas (1)
Stephen23
el 27 de Abr. de 2017
It is not totally clear what you are trying to achieve with that function, as you are both printing the output to the command window using fprintf and you also have defined some function outputs (but you never allocated to these outputs). Judging by the function name the outputs are not required, so I removed the superfluous outputs and added newline characters to the fprintf format strings:
function disp_book(Tit,Aut,Nu_of_pg)
fprintf('Title: %s\n',Tit)
fprintf('Author: %s\n',Aut)
fprintf('Number of pages: %d\n',Nu_of_pg)
end
And tested:
>> disp_book('Dr Seuss','The Cat in the Hat',64)
Title: Dr Seuss
Author: The Cat in the Hat
Number of pages: 64
>>
Categorías
Más información sobre Operations on Strings en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!