Max
Max

Reputation: 1481

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

Using fprintf I want to produce an output that looks like this:

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

This is the code I tried using to achieve this:

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

unfortunatly the output it produces looks like this:

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

Does anyone know how to solve this issue? Or is it even possible to combine fprintf with cell-arrays? Thanks in advance

Upvotes: 3

Views: 278

Answers (2)

Adriaan
Adriaan

Reputation: 18177

The ouput you are seeing is interesting in itself: it resolves abc as a string, then d as it's ASCII number, then ef again as string and g as number, then hi as string, 1 as number and the latter two fizzle as MATLAB can't see 2 as a string. This implies an important thing of fprintf: it takes its arguments in column-major order.

So with that in mind we try creating a cell array of e.g.

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

which unfortunately results in an error that fprintf can't work with cell arrays. I'd go with a trusty for loop:

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

Upvotes: 2

Daniel
Daniel

Reputation: 36710

Take a look at what you are passing to fprintf, it is simply in the wrong order, and numbers creates one parameter not three individual:

>> names{1:3},numbers

ans =

abc


ans =

def


ans =

ghi


numbers =

     1     2     3

Instead use:

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

If you typie in C{:} you will see the individual parameters in order:

>> 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

Upvotes: 4

Related Questions