Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
OPERATIONS ON ARRAY
1) Max (A), Min (A) computes as its name says the maximum of the array A and its minimum
respectively.
2) Sort (A) sorts a vector. You can sort the vector in ascending order or descending order.
E.g. A= [1 -1 2 -2] the code sort (A, descend) gives [2 1 -1 -2]
Exercise: Sort a vector until the middle of it in ascending order, and then in descending order the
remaining part.
Response:
e.g. b= [1 -9 7 2 8 5 10 -1 9 3];
The code z=[sort(b(1:(length(b)/2))),sort(b(length(b)/2+1:length(b)),'descend')] gives
Z = -9
8 10
3 -1
3) Adding a number to an array by <b+ value> increases all elements by that value.
Here b is the previous vector. Mean (b) gives the arithmetic mean, std (b) gives the standard deviation
and sum(b) the sum of all elements.
4) [c, I]=max (b) returns the maximum of the array and its corresponding index.
MATRIX OPERATIONS
Saddle points in matrices:
Lets take for example a payoff matrix resulted from actions of two players in a two-player game:
If we look for a saddle point then we seek if min(max(A))=max(min(A))
If not, we dont have any, if we have then the index is found by the following lines:
1. [b, I]=max(A) // This indicates the position of the maximum in every column.
If I= 2 4 3 1 that means on the first column the maximum is attained on the 2nd row, on the 2nd column
the maximum is attained on the 4th row,etc.
2. run again [b, I]=min(max(A)).That will give you the position in which the minimum is attained
from the maximums shown before. If I=1 that means you have the max(min ) value on the 1st
column and the 2nd row, because from 1) I[1]=2.
2) Find the non-null elements of a matrix A, and the nonnull elements of the diagonal, and the
third column. Count them.
R: find(A),find(diag(A)), find(A(:,3)), and for counting them we use length(find(A))
3) Count how many elements are bigger than a value
Solution: length(find(A>value))
4) Find a way to print out the following triangle
1
1
Solution: S=cell(1,4)
S(1:4)={[1],[1 2],[1 2 3],[1 2 3 4]}
For i=1:4
Disp(S{i}),end.
5. Add to a matrix A a specified number of rows equal to [1 1 1 1]
Solution: After declaring A, we write n=the number desired and
For I = 1:n
A[I + size(A,1),:]=[1 1 1 1]
End.
6. a) Delete a row from the matrix: Response:
A (no,: )=[];
b) Delete more consecutive rows from matrix:
A (no1:no2,: )=[]
c) Delete a selection of rows from a matrix:
E.g. deleting rows 3 and 5 from matrix.
A ([3, 5], : ) = []
d) Delete a selection of columns from a matrix: A(:, [3,5])=[] for example.
7. Print the following output:
1 2
2 3
2 1
Solution: S=cell (3, 1);
S (1:3) = {[1 2];[2 3 4];[2 1]}
For i=1:3
Disp (S {i}), end
8 . Write to a txt file a table containing this information:
29,30,32
33,33,100,91
43,44,91
R: S=cell(3,1);
S(1:3)={[29 30 32];[33 33 100 91];[43 44 91]}
T=table(S);
Writetable(T,text.txt,WriteVariableNames,false)
end
function m = avg(x,n)
m = sum(x)/n;
end