Using MATLAB (779505), страница 27

Файл №779505 Using MATLAB (Using MATLAB) 27 страницаUsing MATLAB (779505) страница 272017-12-27СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 27)

You pass this value as an argument to the other I/O functions to accessthe open file. For example, this fopen statement opens the data file namedpenny.dat for reading.fid = fopen('penny.dat','r')If fopen fails, for example if you try to open a file that does not exist, fopen:• Assigns -1 to the file identifier.• Assigns an error message to an optional second output argument. Note thatthe error messages are system dependent and are not provided for all errorson all systems.

The function ferror may also provide information abouterrors.It’s good practice to test the file identifier each time you open a file in your code.For example, this code loops a readable filename is entered.6-52Using Low-Level File I/O Functionsfid=0;while fid < 1filename=input('Open file: ', 's');[fid,message] = fopen(filename, 'r');if fid == –1disp(message)endendNow assume that nofile.mat does not exist but that goodfile.mat does exist.On one system, the results areOpen file: nofile.matCannot open file. Existence? Permissions? Memory? .

. .Open file: goodfile.matOpening Temporary Files and DirectoriesThe tempdir and tempname commands assist in locating temporary data onyour system.FunctionPurposetempdirGet temporary directory name.tempnameGet temporary filename.You can create temporary files. Some systems delete temporary files every timeyou reboot the system. On other systems, designating a file as temporary maymean only that the file is not backed up.A function named tempdir returns the name of the directory or folder that hasbeen designated to hold temporary files on your system. For example, issuingtempdir on a UNIX system returns the /tmp directory.MATLAB also provides a tempname function that returns a filename in thetemporary directory. The returned filename is a suitable destination fortemporary data. For example, if you need to store some data in a temporary file,then you might issue the following command first.fid = fopen(tempname, 'w');6-536Importing and Exporting DataNote The filename that tempname generates is not guaranteed to be unique;however, it is likely to be so.Reading Binary DataThe fread function reads all or part of a binary file (as specified by a fileidentifier) and stores it in a matrix.

In its simplest form, it reads an entire fileand interprets each byte of input as the next element of the matrix. Forexample, the following code reads the data from a file named nickel.dat intomatrix A.fid = fopen('nickel.dat','r');A = fread(fid);To echo the data to the screen after reading it, use char to display the contentsof A as characters, transposing the data so it displays horizontally.disp(char(A'))The char function causes MATLAB to interpret the contents of A as charactersinstead of as numbers. Transposing A displays it in its more natural horizontalformat.Controlling the Number of Values Readfread accepts an optional second argument that controls the number of valuesread (if unspecified, the default is the entire file). For example, this statementreads the first 100 data values of the file specified by fid into the columnvector A.A = fread(fid,100);Replacing the number 100 with the matrix dimensions [10 10] reads the same100 elements into a 10-by-10 array.Controlling the Data Type of Each ValueAn optional third argument to fread controls the data type of the input.

Thedata type argument controls both the number of bits read for each value andthe interpretation of those bits as character, integer, or floating-point values.6-54Using Low-Level File I/O FunctionsMATLAB supports a wide range of precisions, which you can specify withMATLAB specific strings or their C or Fortran equivalents.Some common precisions include:• ’char’ and ’uchar’ for signed and unsigned characters (usually 8 bits)• 'short' and 'long' for short and long integers (usually 16 and 32 bits,respectively)• 'float' and 'double' for single and double precision floating-point values(usually 32 and 64 bits, respectively)Note The meaning of a given precision can vary across different hardwareplatforms.

For example, a 'uchar' is not always 8 bits. fread also provides anumber of more specific precisions, such as 'int8' and 'float32'. If in doubt,use these precisions, which are not platform dependent. Look up fread inonline help for a complete list of precisions.For example, if fid refers to an open file containing single-precisionfloating-point values, then the following command reads the next 10floating-point values into a column vector A.A = fread(fid,10,'float');Writing Binary DataThe fwrite function writes the elements of a matrix to a file in a specifiednumeric precision, returning the number of values written. For instance, theselines create a 100-byte binary file containing the 25 elements of the 5-by-5magic square, each stored as 4-byte integers.fwriteid = fopen('magic5.bin','w');count = fwrite(fwriteid,magic(5),'int32');status = fclose(fwriteid);In this case, fwrite sets the count variable to 25 unless an error occurs, inwhich case the value is less.6-556Importing and Exporting DataControlling Position in a FileOnce you open a file with fopen, MATLAB maintains a file position indicatorthat specifies a particular location within a file.

MATLAB uses the file positionindicator to determine where in the file the next read or write operation willbegin. The following sections describe how to:• Determine if the file position indicator is at the end of the file• Move to specific location in the file• Retrieve the current location of the file position indicator• Reset the file position indicator to the beginning of the fileDetermining End-of-fileThe fseek and ftell functions let you set and query the position in the file atwhich the next input or output operation takes place:• The fseek function repositions the file position indicator, letting you skipover data or back up to an earlier part of the file.• The ftell function gives the offset in bytes of the file position indicator for aspecified file.The syntax for fseek isstatus = fseek(fid,offset,origin)fid is the file identifier for the file.

offset is a positive or negative offset value,specified in bytes. origin is an origin from which to calculate the move,specified as a string.'bof'Beginning of file'cof'Current position in file'eof'End of fileUnderstanding File PositionTo see how fseek and ftell work, consider this short M-file.A = 1:5;fid = fopen('five.bin','w');fwrite(fid, A,'short');status = fclose(fid);6-56Using Low-Level File I/O FunctionsThis code writes out the numbers 1 through 5 to a binary file named five.bin.The call to fwrite specifies that each numerical element be stored as a short.Consequently, each number uses two storage bytes.Now reopen five.bin for reading.fid = fopen('five.bin','r');This call to fseek moves the file position indicator forward 6 bytes from thebeginning of the file.status = fseek(fid,6,'bof');File PositionFile ContentsFile Position Indicatorbof 10213042506730__↑849010 eof5This call to fread reads whatever is at file positions 7 and 8 and stores it invariable four.four = fread(fid,1,'short');The act of reading advances the file position indicator.

To determine thecurrent file position indicator, call ftell.position = ftell(fid)position =8File PositionFile ContentsFile Position Indicatorbof102130425063708490_↑10 eof5This call to fseek moves the file position indicator back 4 bytes.6-576Importing and Exporting Datastatus = fseek(fid,-4,'cof');File PositionFile ContentsFile Position Indicatorbof 1021304250_↑6370849010 eof5Calling fread again reads in the next value (3).three = fread(fid,1,'short');Reading Strings Line-By-Line from Text FilesMATLAB provides two functions, fgetl and fgets, that read lines fromformatted text files and store them in string vectors. The two functions arealmost identical; the only difference is that fgets copies the newline characterto the string vector but fgetl does not.The following M-file function demonstrates a possible use of fgetl.

Thisfunction uses fgetl to read an entire file one line at a time. For each line, thefunction determines whether an input literal string (literal) appears in theline.If it does, the function prints the entire line preceded by the number of timesthe literal string appears on the line.function y = litcount(filename, literal)% Search for number of string matches per line.fid = fopen(filename, 'rt');y = 0;while feof(fid) == 0tline = fgetl(fid);matches = findstr(tline, literal);num = length(matches);if num > 0y = y + num;fprintf(1,'%d:%s\n',num,tline);endendfclose(fid);6-58Using Low-Level File I/O FunctionsFor example, consider the following input data file called badpoem.Oranges and lemons,Pineapples and tea.Orangutans and monkeys,Dragonflys or fleas.To find out how many times the string 'an'appears in this file, use litcount.litcount('badpoem','an')2: Oranges and lemons,1: Pineapples and tea.3: Orangutans and monkeys,Reading Formatted ASCII DataThe fscanf function is like the fscanf function in standard C.

Both functionsoperate in a similar manner, reading data from a file and assigning it to one ormore variables. Both functions use the same set of conversion specifiers tocontrol the interpretation of the input data.The conversion specifiers for fscanf begin with a % character; commonconversion specifiers include:• %s to match a string• %d to match an integer in base 10 format• %g to match a double-precision floating-point valueYou can also specify that fscanf skip a value by specifying an asterisk in aconversion specifier.

For example, %*f means skip the floating point value inthe input data; %*d means skip the integer value in the input data.Differences Between the MATLAB fscanf and the C fscanfDespite all the similarities between the MATLAB and C versions of fscanf,there are some significant differences. For example, consider a file namedmoon.dat for which the contents are as follows.3.6542345332.713431423145.341341356786-596Importing and Exporting DataThe following code reads all three elements of this file into a matrix namedMyData.fid = fopen('moon.dat','r');MyData = fscanf(fid,'%g');status = fclose(fid);Notice that this code does not use any loops. Instead, the fscanf functioncontinues to read in text as long as the input format is compatible with theformat specifier.An optional size argument controls the number of matrix elements read.

Forexample, if fid refers to an open file containing strings of integers, then thisline reads 100 integer values into the column vector A.A = fscanf(fid,'%5d',100);This line reads 100 integer values into the 10-by-10 matrix A.A = fscanf(fid,'%5d',[10 10]);A related function, sscanf, takes its input from a string instead of a file. Forexample, this line returns a column vector containing 2 and its square root.root2 = num2str([2, sqrt(2)]);rootvalues = sscanf(root2,'%f');6-60Using Low-Level File I/O FunctionsWriting Formatted Text FilesThe fprintf function converts data to character strings and outputs them tothe screen or a file.

A format control string containing conversion specifiers andany optional text specify the output format. The conversion specifiers controlthe output of array elements; fprintf copies text directly.Common conversion specifiers include:• %e for exponential notation• %f for fixed point notation• %g to automatically select the shorter of %e and %fOptional fields in the format specifier control the minimum field width andprecision. For example, this code creates a text file containing a short table ofthe exponential function.x = 0:0.1:1;y = [x; exp(x)];The code below writes x and y into a newly created file named exptable.txt.fid = fopen('exptable.txt','w');fprintf(fid,'Exponential Function\n\n');fprintf(fid,'%6.2f %12.8f\n',y);status = fclose(fid);The first call to fprintf outputs a title, followed by two carriage returns.

Характеристики

Тип файла
PDF-файл
Размер
6,57 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6989
Авторов
на СтудИзбе
262
Средний доход
с одного платного файла
Обучение Подробнее
{user_main_secret_data}