tags:

views:

106

answers:

1

What would be matlab's equivalent of

write(1,'("Speed, resistance, power",3f8.2)')(a(i),i=1,3)

I've tried

a = [10. 20. 200.]
fprintf(unit1,'a = 3%8.1e',a)

but I'm still having trouble with it (the whole matlab output formatting thing).


Edit for Kenny: for the values of a as given above, it would give (in a new row):

Speed, resistance, power   10.00   20.00  200.00
+3  A: 

I'm using 1 for fileID to write to the command window, and I put a newline in the end because it's prettier, but this should reproduce what you want

a = [10,20,200;20,30,300];

fprintf(1,'Speed, resistance, power%8.2f%8.2f%8.2f\n',a')

Speed, resistance, power   10.00   20.00  200.00
Speed, resistance, power   20.00   30.00  300.00

EDIT

Assume an array a of unknown dimensions. Assume further that we want to fprint it row by row

a = [10,20,200;20,30,300];

%# find number of columns
nCols = size(a,2);

%# create format string for fprintf. Use repmat to replicate the %8.2f's
fmtString = ['Speed, resistance, power',repmat('%8.2f',1,nCols),'\n'];

%# print
fprintf(1,fmtString,a')

Speed, resistance, power   10.00   20.00  200.00
Speed, resistance, power   20.00   30.00  300.00

Note: This prints all rows of a one after the other on the same line (thanks, @JS).

fprintf('Speed, resistance,power')
fprintf('%8.2f',a')
fprintf('\n')
Jonas
Okey, that is patch up solution, but what if an array has 10000 elements ? (I just gave three as an example because I didn't feel like making up numbers).
ldigas
@Idigas: If it's a 1000x3 array, it's no problem (see edit). If it's a 1000x1000 array, you need to use `repmat` to repeat the format strings.
Jonas
@Jonas - Aw, crap. I see I'm gonna have a problem with that. The point is, I often don't know how many elements are gonna be in an array, so I just put in the FORMAT specifier a number that I'm sure is larger than the maximum number of elements in an array. In any case, my arrays in all cases have more elements then I would like putting manually in fprintf. Is there no kind of repeat format specifier ? Also, I don't see how repmat command is helpful to me in this ... according to help, it is for duplicating parts of the array.
ldigas
Btw, I appreciate, you, trying to help on this one.
ldigas
@Idigas: no problem. Just use repmat to repeat the %8.2f so that there's one for each column.
Jonas
Alternatively, if only 1 format specifier is given, MATLAB will use that format specifier for all elements in the array. If two are given, it will cycle through the given format specifiers until the array is exhausted.This means you will have to print the prefix string and line break separately, i.e.fprintf(1,'Speed, resistance, power');fprintf(1,'%8.2f',a');fprintf(1,'\n');If you want to print the array in row-column form, you can use a for-loop, or the repmat-specifier solution suggested by Jonas.
JS Ng
@JS: good point - even though this is the behavior of fprintf I usually try to avoid.
Jonas

related questions