MATLAB MATLAB String Operations and File I/O 2 — Questions and Answers
Question 1: What is the correct way to open a file for writing in MATLAB?
- fid = fopen('file.txt', 'w') (Correct answer)
- fid = open('file.txt', 'write')
- fid = fileopen('file.txt')
- fopen('file.txt')
Correct answer: fid = fopen('file.txt', 'w')
fopen opens a file and returns a file identifier; the 'w' mode opens the file for writing, creating it if it does not exist.
Question 2: Which MATLAB function replaces occurrences of a substring within a string?
- strrep (Correct answer)
- replace
- sub
- strreplace
Correct answer: strrep
strrep(str, old, new) replaces all occurrences of the old substring with the new substring in str.
Question 3: What does `fprintf(fid, '%d\n', x)` do in MATLAB?
- Writes formatted integer x followed by newline to the file with identifier fid (Correct answer)
- Prints x to the screen
- Reads an integer from file fid
- Formats x as a float
Correct answer: Writes formatted integer x followed by newline to the file with identifier fid
fprintf writes data to a file or screen using C-style format specifiers, with fid=1 for stdout and fid=2 for stderr.
Question 4: How do you split a string by a delimiter in MATLAB?
- strsplit(str, delimiter) (Correct answer)
- split(str, delimiter)
- explode(str, delimiter)
- strcut(str, delimiter)
Correct answer: strsplit(str, delimiter)
strsplit splits a string at each occurrence of the specified delimiter and returns a cell array of substrings.
Question 5: Which function converts a string to lowercase in MATLAB?
- lower (Correct answer)
- tolower
- strlower
- lcase
Correct answer: lower
lower converts all uppercase letters in a string to their lowercase equivalents.
Question 6: What does `xlswrite('data.xlsx', M)` do in MATLAB?
- Writes matrix M to an Excel file named data.xlsx (Correct answer)
- Reads data from data.xlsx into M
- Appends M to an existing Excel sheet
- Converts M to XML format
Correct answer: Writes matrix M to an Excel file named data.xlsx
xlswrite writes array data to an Excel spreadsheet file, creating it if it does not exist.
What is the correct way to open a file for writing in MATLAB?