使用sprintf打印具有可变数量元素的向量 [英] Print a vector with variable number of elements using sprintf

查看:68
本文介绍了使用sprintf打印具有可变数量元素的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我可以将向量item中的所有元素打印为一个空格

In the following code, I can print all the elements in the vector item separated by a space as

item = [123 456 789];
sprintf('%d %d %d', item)

ans =

123 456 789

如何执行此操作而不必输入与item中的元素数一样多的%d?

How do I go about doing this without having to enter as many %d as the number of elements in item?

推荐答案

最简单的答案是注意 SPRINTF 自动循环遍历您提供的向量的所有元素,因此您只需要使用 one %d,但可以遵循或引导它与空间.然后,您可以使用 STRTRIM 消除两端多余的空格.例如:

The simplest answer is to note that SPRINTF will automatically cycle through all the elements of a vector you give it, so you only have to use one %d, but follow it or lead it with a space. Then you can remove extra white space on the ends using the function STRTRIM. For example:

>> item = [123 456 789];
>> strtrim(sprintf('%d ',item))

ans =

123 456 789

这篇关于使用sprintf打印具有可变数量元素的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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