将 fprintf 与双数组和元胞数组结合使用

Using fprintf with a combination of a double-array and a cell-array

使用 fprintf 我想生成如下所示的输出:

names abc and numbers 1
names def and numbers 2
names ghi and numbers 3

这是我尝试使用的代码:

names= {'abc','def','ghi'}
numbers = [1 2 3];
fprintf('names %s and numbers %2.2f \n',names{1:3},numbers)

不幸的是,它产生的输出如下所示:

names abc and numbers 100.00
names ef and numbers 103.00
names hi and numbers 1.00
names and number

有谁知道如何解决这个问题?或者甚至可以将 fprintf 与元胞数组结合使用?提前致谢

您看到的输出本身很有趣:它将 abc 解析为字符串,然后将 d 解析为 ASCII 数字,然后 ef 再次解析为字符串,然后 g 作为数字,然后 hi 作为字符串,1 作为数字,后两个失败,因为 MATLAB 无法将 2 视为字符串。这暗示了 fprintf 的一件重要事情:它以列优先顺序接收参数。

考虑到这一点,我们尝试创建一个元胞数组,例如

for ii=numel(numbers)-1:1
    tmp{ii,2} = numbers(ii);
    tmp{ii,1} = names{ii};
end

不幸的是,这会导致 fprintf 无法使用元胞数组的错误。我会选择一个可靠的 for 循环:

names= {'abc','def','ghi'} ;
numbers = [1 2 3];
for ii=1:numel(numbers)
    fprintf('names %s and numbers %2.2f \n',names{ii},numbers(ii))
end

names abc and numbers 1.00
names def and numbers 2.00
names ghi and numbers 3.00

看看您传递给 fprintf 的内容,只是顺序错误,数字创建一个参数而不是三个单独的参数:

>> names{1:3},numbers

ans =

abc


ans =

def


ans =

ghi


numbers =

     1     2     3

改为使用:

C=names
C(2,:)=num2cell(numbers)
fprintf('names %s and numbers %2.2f \n',C{:})

如果您输入 C{:},您将按顺序看到各个参数:

>> fprintf('names %s and numbers %2.2f \n',C{:})
names abc and numbers 1.00 
names def and numbers 2.00 
names ghi and numbers 3.00 

>> C{:}

ans =

abc


ans =

     1


ans =

def


ans =

     2


ans =

ghi


ans =

     3