如何在MATLAB中将变量值放入文本字​​符串中? [英] How do I put variable values into a text string in MATLAB?

查看:275
本文介绍了如何在MATLAB中将变量值放入文本字​​符串中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简单的函数,该函数接受两个输入xy,并将它们传递给其他三个简单函数,这些函数对它们进行加,乘和除.然后,主函数应将结果显示为包含xy和总数的字符串.

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;

主要功能是:

function [d e f]=answer(x,y)
d=addxy(x,y);
e=mxy(x,y);
f=dxy(x,y);
z=[d e f]

如何将xydef的值转换为字符串?我尝试了不同的矩阵和类似的东西:

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]

但没有显示任何变量.

另外两个问题:

  • 即使我没有要求输入z的长度,为什么函数仍返回"ans 3"?
  • 如果有人能为MATLAB脚本初学者推荐一本好书,我将不胜感激.
  • Why is the function returning "ans 3" even though I didn't ask for the length of z?
  • If anyone could recommend a good book for beginners to MATLAB scripting I'd really appreciate it.

推荐答案

作为 Amro 说明,您必须先将数字值转换为格式化的字符串,才能显示它们或将它们与其他字符串连接.您可以使用 FPRINTF SPRINTF

As Peter and Amro illustrate, you have to convert numeric values to formatted strings first in order to display them or concatenate them with other character strings. You can do this using the functions FPRINTF, SPRINTF, NUM2STR, and INT2STR.

关于将ans = 3作为输出,可能是因为您没有将answer的输出分配给变量.如果要获取所有输出值,则必须通过以下方式调用answer:

With respect to getting ans = 3 as an output, it is probably because you are not assigning the output from answer to a variable. If you want to get all of the output values, you will have to call answer in the following way:

[out1,out2,out3] = answer(1,2);

这会将值d放置在out1中,将值e放置在out2中,并将值f放置在out3中.当您执行以下操作时:

This will place the value d in out1, the value e in out2, and the value f in out3. When you do the following:

answer(1,2)

MATLAB将自动将第一个输出d(在这种情况下,其值为3)分配给默认工作空间变量

MATLAB will automatically assign the first output d (which has the value 3 in this case) to the default workspace variable ans.

关于建议学习MATLAB的良好资源,您不应低估MATLAB文档的价值.我已经学会了自己使用它的大部分知识.您可以在线或在副本中访问它使用 DOC HELP

With respect to suggesting a good resource for learning MATLAB, you shouldn't underestimate the value of the MATLAB documentation. I've learned most of what I know on my own using it. You can access it online, or within your copy of MATLAB using the functions DOC, HELP, or HELPWIN.

这篇关于如何在MATLAB中将变量值放入文本字​​符串中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆