mac389
mac389

Reputation: 3133

Writing a list of variables and their values from Matlab to text

I'm trying to write something like the following to file.

keys = {'one','two','three'}
values = [1 2 3]

This is my code so far:

function save_recording_results(keys,values)
    keys=keys.';
    fid = fopen('hoping', 'wt');
    fprintf(fid, '%s : %f\n', keys{:},values);
    fclose(fid);
end

My output is this:

one : 116.000000 
wo : 116.000000
hree : 1.000000
:

I want it to look like this:

one : 1
two : 2
three : 3

I'm not sure what I'm doing wrong. Why does it drop the first character? This happens even when the first character isn't 't'. I gather that what it is doing is printing the first letter of the (n+1)th variable on the line for the nth variable after the colon. (T is 116 in ASCII.) But, why?

Upvotes: 1

Views: 195

Answers (2)

carandraug
carandraug

Reputation: 13091

What's happening is that when you have keys{:} you are returning a cs-list. Basically what you are doing is this

printf ('%s : %f\n', 'one', 'two', 'three', [1 2 3]);

Experiment typing keys{:} to understand what I mean by a cs-list (comma separated list).

So when interpreting your formatting, the first time it expects a string (%s) and it works fine because it finds "one". The second time expects a floating (%f) but gets a string ("two"). So converts it into a vector double ("two"), which is [116 119 111] and uses the first for the floating. Then it expects another string (second line). The "t" was taken before (converted to floating), so it only has "wo" which it uses for the string. And so on, and so on until the end.

Here's how to do it correctly. You have to make a new cell array with 2 columns. The following should work just fine.

values = num2cell (values);
new    = {keys{:}; values{:}}
printf ('%s : %f\n', new{:})

Upvotes: 1

AGS
AGS

Reputation: 14498

If you aren't opposed to using a loop:

fid = fopen('hoping', 'wt');    
for a = 1:length(keys)
  fprintf (fid,'%s : %d\n', keys{a},values(a))
end
fclose(fid)

Upvotes: 1

Related Questions