Learning data science in MATLAB serves as an excellent foundation for your research and data science project. MATLAB’s ease of use and similarity to standard linear algebra notation can be helpful to learn the fundamental mathematical concepts every Data Scientist will encounter in his/her Data Science career. Follow along and check the 35 most common and advanced MATLAB Interview Questions and Answers you must know before your next Data Science Interview.
There are several differences between a Cell Array and a Matrix in MATLAB:
2 is that when you resize a matrix every element in the matrix must be copied over to the newly allocated memory area, but in the case of a cell array only a list of pointers needs to copied over. Depending on the size and type of elements you're storing, this might mean cell arrays are much faster to resize.* and .* in MATLAB?* is a vector or matrix multiplication, in order to use this operator, the operands should obey matrix multiplication rules in terms of size..* is a element-wise multiplication. In order to use this operator, vector lengths or matrix sizes should be equal.For example,
a = [ 1; 2]; % column vector
b = [ 3 4]; % row vector
a*b
ans =
3 4
6 8while
a.*b.' % .' means tranpose
ans =
3
8A in B and get the index of the found element in BI have two arrays, A and B. Find every instance when an element in A equals B and get the index of B when this occurs.
A = [4 4 8 9 7 2 32 5 45 98 7 1 3 3 3]
B = [4 8 9 8 7 7 5 12 32 56 74 12 75 2 7 4]Consider that elements of A might occur once, others multiple times, and some not at all. Therefore we need to resort to cell arrays and then with arrayfun, you can loop over all elements of A to find the coincidences and store them in C.
C = arrayfun(@(x) find(B==x), A, 'un', 0)Now C{k} holds the indices into B, where B equals A(k). For example, A(1) = 4 and C{1} = 1 16, i.e., B(1) and B(16) are equal to 4.
n-dimensional matrix in MATLAB?We can iterate over all elements in a matrix A (of any dimension) using a linear index from 1 to numel(A) in a single for loop.
for idx = 1:numel(A)
element = A(idx)
...
end1x1 cell to a character vector or string?To convert a cell array of character vectors to a character array, we use the char function.
A = {'line'}
B = char(A)We could also extract the contents from a cell, index using curly braces.
A = {'line'}
B = A{1}Finally, to convert a cell array to a string array, we use the string function.
A = {'line'}
B = string(A) The min and max functions in MATLAB return the index of the minimum and maximum values, respectively, as an optional second output argument.
For example, the following code produces a row vector 'M' that contains the maximum value of each column of 'A', which is 3 for the first column and 4 for the second column. Additionally, 'I' is a row vector containing the row positions of 3 and 4, which are 2 and 2, since the maximums for both columns lie in the second row.
>> A = [1 2; 3 4]
A =
1 2
3 4
>> [M,I] = max(A)
M =
3 4
I =
2 2To get the type of variable we use the class function.
>> b = 2
>> a = 'Hi'
>> class(b)
ans =
double
>> class(a)
ans =
charAssume you have the following data matrix:
A =
1 11 22 33
44 13 12 33
1 14 33 44Delete all rows of this matrix that don't accomplish the condition A(:, 4) == 33 and get the matrix of this form which only selects these rows:
A_new =
1 11 22 33
44 13 12 33Using logical indexing, this can be achieved as follows
A = [
1 11 22 33
44 13 12 33
1 14 33 44
];
idx = ( A(:,4)==33 );
A_new = A(idx,:)Output:
A_new =
1 11 22 33
44 13 12 33() and curly braces {}?Think of cell array as a regular homogenous array, whose elements are all cells. Parentheses (()) simply access the cell wrapper object, while accessing elements using curly bracers ({}) gives the actual object contained within the cell.
For example,
A={ [5,6], 0 , 0 ,0 };It will look like this:
The syntax of making an element equal to [] with parentheses is a request to delete that element, so when you ask to do foo(i) = [] you remove the i-th cell. It is not an assignment operation, but rather a RemoveElement operation, which uses similar syntax to assignment.
However, when you do foo{i} = [] you are assigning to the i-th cell a new value (which is an empty array), thus clearing the contents of that cell.
& and && logical operators in MATLAB?The single ampersand & is the logical AND operator and it can operate on arrays in an element-wise fashion. A & B means that A and B are evaluated.
The double ampersand && is again a logical AND operator that employs short-circuiting behavior. Short-circuiting just means the second operand (right-hand side) is evaluated only when the result is not fully determined by the first operand (left-hand side). In other words, A && B means that B is only evaluated if A is true. These can only operate on scalars, not arrays.
Program files can contain multiple functions, their types are:
Local functions: are subroutines that are available within the same file. Local functions are the most common way to break up programmatic tasks. In a function file, which contains only function definitions, local functions can appear in the file in any order after the main function in the file. In a script file, which contains commands and function definitions, the local function must be at the end of the file.
Nested functions: are completely contained within another function. The primary difference between nested functions and local functions is that nested functions can use variables defined in parent functions without explicitly passing those variables as arguments. They are useful when subroutines share data, such as applications that pass data between components.
Private Functions: are functions that exist in a subfolder named private, so they are available only to functions in the folder immediately above the private folder. These functions are used to separate code into different files or to share code between multiple, related functions.
Anonymous Functions: allow us to define a function without creating a program file, as long as the function consists of a single statement. A common application of anonymous functions is to define a mathematical expression, and then evaluate that expression over a range of values using a function handle.
who and whos in MATLAB?who lists in alphabetical order the names of all variables in the currently active workspace.whos lists in alphabetical order the names, sizes, and types of all variables in the currently active workspace.>> FIRST = 10
>> SECOND = 90
>> THIRD = FIRST + SECOND
>> vector = [10 20 30 40 50 60 70 80 90 100]
>> who
Your variables are:
FIRST SECOND THIRD vector
>> whos
Name Size Bytes Class Attributes
FIRST 1x1 8 double
SECOND 1x1 8 double
THIRD 1x1 8 double
vector 1x10 80 doubleIs better to use Cell Arrays when:
CELLFUN function.Is better to use Structs when:
You need to store data (and return an output), since the field names are (should be) self-documenting, so you don't need to remember what information you had in column 7 of a cell array. Also, you can easily include a field 'help' in your structure where you can put some additional explanation of the fields, if necessary.
You want to update your code at a later date, replace them with objects without needing to change your code (at least in case you did pre-assignment of your structure). They have the same syntax, but objects will allow you to add more functionality, such as dependent properties (i.e. properties that are calculated on the fly based on other properties).
In the end, it's also a matter of convenience and code clarity. If you prefer to refer your variable elements by number(s) or by name. Then use cell array in the former case and struct array in later.
Giving two vectors, V and N:
>> rng(42)
>> numberOfRows = 5;
>> V = rand(numberOfRows, 1)
>> N = rand(numberOfRows, 1)The goal is to find the closest distance between N and V.
% Find min distance
minDistance = inf;
for ni = 1 : numberOfRows
for vi = 1 : numberOfRows
distances(vi, ni) = abs(N(ni) - V(vi));
if distances(vi, ni) < minDistance
minNRow = ni;
minVRow = vi;
minDistance = distances(vi, ni);
end
end
end
% Report to command window:
distances
fprintf('The closest distance is %f which occurs between row %d of N and row %d of V\n',...
minDistance, minNRow, minVRow);In the command window:
V =
0.3745
0.9507
0.7320
0.5987
0.1560
N =
0.1560
0.0581
0.8662
0.6011
0.7081
distances =
0.2185 0.3165 0.4916 0.2266 0.3335
0.7947 0.8926 0.0845 0.3496 0.2426
0.5760 0.6739 0.1342 0.1309 0.0239
0.4427 0.5406 0.2675 0.0025 0.1094
0.0000 0.0979 0.7102 0.4451 0.5521
The closest distance is 0.000024 which occurs between row 1 of N and row 5 of VI have a matrix A with n values spanning from 65:90. How do i get the 5 most common values in A? I want the result to be a 5x2 matrix B with the 5 common values in the first column and the times it appears in the second column.
A = [65 82 65 90 75;
90 70 72 82 81;
45 56 95 80 41;
65 82 12 4 45]To solve this problem we can use the histc function which counts the number of values that are within each specified range.
range = 65:90;
res = [range; histc(A(:)', range)]'; % res has values in first column, counts in second.Now we sort the res array by the second column and take the first 5 rows.
sortedres = sortrows(res, -2); % sort by second column, descending
first5 = sortedres(1:5, :)Output:
first5 =
65 3
82 3
90 2
70 1
72 1One way is performing a time control with the tic and toc functions. For example, if code takes an hour, then break the loop:
% for loop
time0 = tic;
timeLimit = 60*60*1; % 1 hour == 3600 seconds
for ...
...
if toc(time0)>timeLimit
break
end
endor using while loop:
time0 = tic;
timeLimit = 60*60*1; % 1 hour == 3600 seconds
while conds && toc(time0)<timeLimit
...
endIn case of placing multiple breakpoints it is vital to identify them e.g. by printing breakpoint info. It is crucial to design breakpoints in a way allowing to resume computations from the point it was disrupted. Sometimes instead of a command break it is better to put a message and a debugger breakpoint which will give you command-line access while the program is paused. Then you can continue from this exact point in code.
There are three types of breakpoints:
F12 key. Let A a matrix (of any dimension) and my_func a function. We first create a function handle to my_func, and then we use arrayfun to apply my_func to each element of A:
fcn = @my_func;
outArgs = arrayfun(fcn, A);Now, let A a cell array of arbitrary dimension. We can use cellfun to apply my_func to each cell:
outArgs = cellfun(fcn, A);The function my_func has to accept A as an input. If there are any outputs from my_func, these are placed in outArgs, which will be the same size/dimension as A.
One caveat on outputs: if my_func returns outputs of different sizes and types when it operates on different elements of A, then outArgs will have to be made into a cell array. This is done by calling either arrayfun or cellfun with an additional parameter/value pair:
outArgs = arrayfun(fcn, A, 'UniformOutput', false);
outArgs = cellfun(fcn, A, 'UniformOutput', false);We can assign values to the diagonal of a matrix with the eye function.
rng(42)
A = magic(4)
values = [1,2,3,4]
A(logical(eye(size(A)))) = valuesOutput:
A =
1 2 3 13
5 2 10 8
9 7 3 12
4 14 15 4There are a few different options on how to do this. The most basic is to use varargin, and then use nargin, size etc. to determine whether the optional arguments have been passed to the function.
% Function that takes two arguments, X & Y, followed by a variable number of additional arguments
function varlist(X,Y,varargin)
fprintf('Total number of inputs = %d\n',nargin);
nVarargs = length(varargin);
fprintf('Inputs in varargin(%d):\n',nVarargs)
for k = 1:nVarargs
fprintf(' %d\n', varargin{k})
endTo create Constants properties you should declare the Constant attribute in the property blocks. Setting the Constant attribute means that, once initialized to the value specified in the property block, the value cannot be changed. For example, let's create a class to perform degree to radian conversion:
classdef NamedConst
properties (Constant)
R = pi/180
D = 1/NamedConst.R
end
endTo referencing the constant properties, refer to the constant using the class name and the property name, i.e. ClassName.PropName. For example,
>> radi = 45*NamedConst.R
radi =
0.7854containers.Map?Iterate over the keys and elements of D:
D = containers.Map({'2R175', 'B7398', 'A479GY', 'NZ1452'}, ...
{'James Enright', 'Carl Haynes', 'Sarah Latham', ...
'Bradley Reid'});{}. k = keys(D) ;
val = values(D) ;
for i = 1:length(D)
[k{i} val{i}]
endOutput:
ans =
'2R175James Enright'
ans =
'A479GYSarah Latham'
ans =
'B7398Carl Haynes'
ans =
'NZ1452Bradley Reid'I have a structure with many fields which are vectors of different lengths. I would like to access the fields within a loop, in order.
>> S = struct('A', [1 2], 'B',[3 4 5]);
SNames = fieldnames(S);
% complete codeWe use dynamic field reference, where you put a string in the parenthesis as seen on the line defining stuff.
>> for loopIndex = 1:numel(SNames) % Loop over the number of cells
stuff = S.(SNames{loopIndex}) % Access the contents of each cell
end
stuff =
1 2
stuff =
3 4 5foreach in MATLAB? If so, how does it behave if the underlying data changes?MATLAB's FOR loop is static in nature; you cannot modify the loop variable between iterations, unlike the for(initialization;condition;increment) loop structure in other languages. This means that the following code always prints 1, 2, 3, 4, 5 regardless of the value of B.
A = 1:5;
for i = A
A = B;
disp(i);
endIf you want to be able to respond to changes in the data structure during iterations, a WHILE loop may be more appropriate, you'll be able to test the loop condition at every iteration, and set the value of the loop variable(s) as you wish:
n = 10;
f = n;
while n > 1
n = n-1;
f = f*n;
end
disp(['n! = ' num2str(f)])Categorical arrays are convenient and memory-efficient containers for non-numeric data with values from a finite set of discrete categories. They are especially useful when the categories have a meaningful mathematical ordering, such as an array with entries from the discrete set of categories {'small','medium','large'} where small < medium < large.
An ordering other than alphabetical order is not possible with character arrays. Thus, inequality comparisons, such as greater and less than, are not possible. With categorical arrays, you can use relational operations to test for equality and perform element-wise comparisons that have a meaningful mathematical ordering.
Furthermore, to compare values in Character arrays, you must use the strcmp function which can be cumbersome. With categorical arrays, you can use the logical operator eq (==) to compare elements in the same way that you compare numeric arrays.
When using a Character array as a categorical array the categories are defined as character vectors, which can be costly to store and manipulate. Categorical arrays store only one copy of each category name, often reducing the amount of memory required to store the array.
linspace vs the colon : operator for creating vectors in MATLAB?linspace and the colon operator ; do different things:
linspace creates a vector of the specified length, and then scales it down to the specified interval with a division. In this way it ensures that the output vector is as linearly spaced as possible.
The colon operator (:) adds increments to the starting point, and subtracts decrements from the end point to reach a middle point. In this way, it ensures that the output vector is as symmetric as possible.
The two methods thus have different aims, and will often give very slightly different answers, e.g.
>> a = 0:pi/1000:10*pi;
>> b = linspace(0,10*pi,10001);
>> all(a==b)
ans =
0
>> max(a-b)
ans =
3.5527e-15In practice, however, the differences will often have little impact unless you are interested in tiny numerical details. linspace is more convenient when the number of gaps is easy to express, whereas the colon operator : is more convenient when the increment is easy to express.
In short,
This means that in a regular array all of the elements are of the same type, whereas in a cell array, they can be different.
It's better to use Cell Array when:
(n,m).And prefer Regular Array when:
eval function in MATLAB?Amazone runs the internet as we know it. Amazon Web Services (AWS) offers a comprehensive suite of machine learning (ML) services that cater to various needs and expertise levels. Follow along and learn the 23 most common AWS machine-learning intervi...
Azure Machine Learning (Azure ML) is a cloud-based service for creating and managing machine learning solutions. It’s designed to scale, distribute, and deploy machine learning models to the cloud. Follow along and learn the 23 most common Azure Mach...
Hadoop is an open-source big data processing framework. It leverages distributed computing to store and process large datasets in a fault-tolerant manner. According to recent reports, Apache Hadoop is one of the most sought-after big data skills with...