Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
5 семестр / MATLAB / Задание / METOD / Ввод данных.doc
Скачиваний:
41
Добавлен:
24.02.2016
Размер:
76.29 Кб
Скачать

Вывод данных

  1. Вывод сообщений на экран

DISPотображает массив.

DISP(X) отображает массив без вывода имени массива. В остальном – это то же самое, как написать просто выражение, включающее имя массива (за исключением того, что пустой массив не отображается.

Если X– символьная строка, отображается текст.

Например,

> d=5

d =

5

>> disp(6*d+8)

38

>> 6*d+8

ans =

38

Или

>> disp(['days=' int2str(d)])

days=5

Функции преобразования: int2str, num2str, sprintf, mat2str, eval

SPRINTFЗаписывает форматированные данные в символьную строку.

sprintf('%0.5g',(1+sqrt(5))/2) 1.618

sprintf('%0.5g',1/eps) 4.5036e+15

sprintf('%15.5f',1/eps) 4503599627370496.00000

sprintf('%d',round(pi)) 3

sprintf('%s','hello') hello

sprintf('The array is %dx%d.',2,3) The array is 2x3.

sprintf('\n') is the line termination character on all platforms.

MAT2STRПреобразует двумерную матрицу в строку в синтаксисеMATLAB.

STR=MAT2STR(MAT) преобразует матрицуMATв строкуMATLAB

Так, что EVAL(STR) приведет к исходной матрице (с точностью до 15 знаков). Нескалярные матрицы преобразуются в строки, содержащие скобки [].

  1. Вывод в файл

    1. Вывод числовых данных

save '<имя файла>' XY– сохранение переменныхX,Y,… в бинарном виде в файле с именем <имя файла>.MAT.

save '<имя файла>' XASCII- запись в текстовый файл с заданным именем <имя файла> содержимого переменной Х с одинарной точностью.

save '<имя файла>' XASCII-DOUBLE- запись в текстовый файл с заданным именем <имя файла> содержимого переменной Х с двойной точностью.

    1. Форматный вывод на экран или в файл

<Файловая переменная> = fopen(<имя файла>,’w’)

Вывод на экран

[<имя переменной>=]fprintf(‘<формат вывода>’,<список вывода>)

Имя переменной – если нужно определить сколько байт (знаков) фактически выведено на экран.

Например, вывод переменной с 1 значением

>> fprintf('Value of a=%d\n',a)

Value of a=11

Вывод вектора b=(1 2 3 4 5)

>> fprintf('%d',b)

12345

>> fprintf('%d\n',b)

1

2

3

4

5

fprintf('%d %d %d\n',b)

1 2 3

4 5

>> asd=fprintf('%d %d %d\n',b)

1 2 3

4 5

asd=

10

Вывод в файл

DLMWRITEЗаписывает данные в текстовый файл с разделителями.

DLMWRITE('FILENAME',M) записывает матрицуMв файлFILENAMEс использованием разделителя ',' между элементами матрицы.

DLMWRITE('FILENAME',M,'DLM') записывает матрицуMвFILENAMEс использованием символаDLMв качестве разделителя.

DLMWRITE('FILENAME',M,'DLM',R,C) записывает матрицуM, начиная со строкиR, и столбцаCв файл. ЗдесьRиC– начинаются с нуля, так чтоR=C=0 определяют первое значение в файле.

DLMWRITE('FILENAME',M,'ATTRIBUTE1','VALUE1','ATTRIBUTE2','VALUE2'...)

An alternative calling syntax that uses attribute value pairs for

specifying optional arguments to DLMWRITE. The order of the

attribute-value pairs does not matter, as long as an appropriate value

follows each attribute tag.

DLMWRITE('FILENAME',M,'-append') appends the matrix to the file.

without the flag, DLMWRITE overwrites any existing file.

DLMWRITE('FILENAME',M,'-append','ATTRIBUTE1','VALUE1',...)

Is the same as the previous syntax, but accepts attribute value pairs,

as well as the '-append' flag. The flag can be placed in the argument

list anywhere between attribute value pairs, but not between an

attribute and its value.

USER CONFIGURABLE OPTIONS

ATTRIBUTE : a quoted string defining an Attribute tag. The following

attribute tags are valid -

'delimiter' => Delimiter string to be used in separating matrix

elements.

'newline' => 'pc' Use CR/LF as line terminator

'unix' Use LF as line terminator

'roffset' => Zero-based offset, in rows, from the top of the

destination file to where the data it to be

written.

'coffset' => Zero-based offset, in columns, from the left side

of the destination file to where the data is to be

written.

'precision' => Numeric precision to use in writing data to the

file, as significant digits or a C-style format

string, starting with '%', such as '%10.5f'. Note

that this uses the operating system standard

library to truncate the number.

EXAMPLES:

DLMWRITE('abc.dat',M,'delimiter',';','roffset',5,'coffset',6,...

'precision',4) writes matrix M to row offset 5, column offset 6, in

file abc.dat using ; as the delimiter between matrix elements. The

numeric precision is of the data is set to 4 significant decimal

digits.

DLMWRITE('example.dat',M,'-append') appends matrix M to the end of

the file example.dat. By default append mode is off, i.e. DLMWRITE

overwrites the existing file.

DLMWRITE('data.dat',M,'delimiter','\t','precision',6) writes M to file

'data.dat' with elements delimited by the tab character, using a precision

of 6 significant digits.

DLMWRITE('file.txt',M,'delimiter','\t','precision','%.6f') writes M

to file file.txt with elements delimited by the tab character, using a

precision of 6 decimal places.

DLMWRITE('example2.dat',M,'newline','pc') writes M to file

example2.dat, using the conventional line terminator for the PC

platform.

Соседние файлы в папке METOD