MATLAB Language Getting started with MATLAB Language Reading Input & Writing Output


Just like all programming language, Matlab is designed to read and write in a large variety of formats. The native library supports a large number of Text,Image,Video,Audio,Data formats with more formats included in each version update - check here to see the full list of supported file formats and what function to use to import them.

Before you attempt to load in your file, you must ask yourself what do you want the data to become and how you expect the computer to organize the data for you. Say you have a txt/csv file in the following format:


We can see that the first column is in the format of Strings, while the second, third are Numeric, the last column is in the form of Currency. Let's say we want to find how much revenue we made today using Matlab and first we want to load in this txt/csv file. After checking the link, we can see that String and Numeric type of txt files are handled by textscan. So we could try:

fileID = fopen('dir/test.txt'); %Load file from dir
C = textscan(fileID,'%s %f %f %s','Delimiter',',','HeaderLines',1); %Parse in the txt/csv

where %s suggest that the element is a String type, %f suggest that the element is a Float type, and that the file is Delimited by ",". The HeaderLines option asks Matlab to skip the First N lines while the 1 immediately after it means to skip the first line (the header line).

Now C is the data we have loaded which is in the form of a Cell Array of 4 cells, each containing the column of data in the txt/csv file.

So first we want to calculate how many fruits we sold today by subtracting the third column from the second column, this can be done by:

sold = C{2} - C{3}; %C{2} gives the elements inside the second cell (or the second column)

Now we want to multiply this vector by the Price per unit, so first we need to convert that column of Strings into a column of Numbers, then convert it into a Numeric Matrix using Matlab's cell2mat the first thing we need to do is to strip-off the "$" sign, there are many ways to do this. The most direct way is using a simple regex:

D = cellfun(@(x)(str2num(regexprep(x, '\$',''))), C{4}, 'UniformOutput', false);%cellfun allows us to avoid looping through each element in the cell.

Or you can use a loop:

for t=1:size(C{4},1)
   D{t} = str2num(regexprep(C{4}{t}, '\$',''));

E = cell2mat(D)% converts the cell array into a Matrix

The str2num function turns the string which had "$" signs stripped into numeric types and cell2mat turns the cell of numeric elements into a matrix of numbers

Now we we can multiply the units sold by the cost per unit:

revenue = sold .* E; %element-wise product is denoted by .* in Matlab

totalrevenue = sum(revenue);