I'm trying to write a simple function that takes two inputs, x
and y
, and passes these to three other simple functions that add, multiply, and divide them. The main function should then display the results as a string containing x
, y
, and the totals.
I think there's something I'm not understanding about output arguments. Anyway, here's my (pitiful) code:
function a=addxy(x,y)
a=x+y;
function b=mxy(x,y)
b=x*y;
function c=dxy(x,y)
c=x/y;
The main function is:
function [d e f]=answer(x,y)
d=addxy(x,y);
e=mxy(x,y);
f=dxy(x,y);
z=[d e f]
How do I get the values for x
, y
, d
, e
, and f
into a string? I tried different matrices and stuff like:
['the sum of' x 'and' y 'is' d]
but none of the variables are showing up.
Two additional issues:
z
?disp( X ) displays the value of variable X without printing the variable name. Another way to display a variable is to type its name, which displays a leading “ X = ” before the value.
chr = int2str( N ) treats N as a matrix of integers and converts it to a character array that represents the integers.
String arrays provide a set of functions for working with text as data. You can create strings using double quotes, such as str = "Greetings friend" . To convert data to string arrays, use the string function.
%s represents character vector(containing letters) and %f represents fixed point notation(containining numbers). In your case you want to print letters so if you use %f formatspec you won't get the desired result.
I just realized why I was having so much trouble - in MATLAB you can't store strings of different lengths as an array using square brackets. Using square brackets concatenates strings of varying lengths into a single character array.
>> a=['matlab','is','fun']
a =
matlabisfun
>> size(a)
ans =
1 11
In a character array, each character in a string counts as one element, which explains why the size of a is 1X11.
To store strings of varying lengths as elements of an array, you need to use curly braces to save as a cell array. In cell arrays, each string is treated as a separate element, regardless of length.
>> a={'matlab','is','fun'}
a =
'matlab' 'is' 'fun'
>> size(a)
ans =
1 3
Here's how you convert numbers to strings, and join strings to other things (it's weird):
>> ['the number is ' num2str(15) '.']
ans =
the number is 15.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With