Multiply inverse matrix with another one - matlab

I want to multiply two matrices, the first matrix is the inverse of A, and the second matrix is B,
input('Enter The first Matrix')
A = [ 1 2 3 ; 4 5 6 ; 7 8 0 ]
[m n] = size(A)
if m==n
if det(A)==0
disp('inverse does not exist')
else
invv=inv(A)
disp(invv)
end
else
disp('Number of rows and columns are not equel , no inverse')
end
input('Enter The second Matrix')
B = [ 1 ; 1 ; 1 ]
How can I verify that the number of columns in the first matrix is equal to the number of rows in the second matrix, so that they can be multiplied?

function [X] = dot_inv(X,x)
% X - numeric array
% x - cell array of numeric vectors
% DIM - dimensions to omit (asumes ndims(X) = numel(x))
% Y - inner product obtained by summing the products of X and x along DIM
% initialise dimensions
%--------------------------------------------------------------------------
[m n] = size(X)
if m==n
if det(X)==0
error('Error. \n inverse does not exist.')
else
X=inv(X)
end
else
error('Error. \n Number of rows and columns are not equel , no inverse!')
end
if iscell(x)
DIM = (1:numel(x)) + ndims(X) - numel(x);
else
DIM = 1;
x = {x};
end
% inner product using recursive summation (and bsxfun)
%--------------------------------------------------------------------------
for d = 1:numel(x)
s = ones(1,ndims(X));
s(DIM(d)) = numel(x{d});
X = bsxfun(#times,X,reshape(full(x{d}),s));
X = sum(X,DIM(d));
end
% eliminate singleton dimensions
%--------------------------------------------------------------------------
X = squeeze(X);
return

Related

Return and call multiple value from function

I am trying to return all values of for loop from my function and also I need to call them outside of the function.But i only get last row of the for loop, I also need previous result of for loop.
Here is my code
i=input('Enter a start row: ');
j=input('Enter a end row: ');
c=input('Enter classifier variable column number:')
search= importfiledataset('search-queries-features.csv',i,j);
[n,p]=size(search);
if j>n
disp('Please enter a smaller number!');
end
[D1,Eps1]=findD(i,j,c,search);
disp(D1);
disp(n1);
function [D1,Eps1] = findD(i,j,c,search) %Find D vlaues with for loop for each classification value
for numOfClassifier = 1 : 100
a = search(search(:,c)==numOfClassifier,:) ;
q1 = a(all(~isnan(a),2),:); % for nan - rows
D1 = a(:,all(~isnan(a))) % for nan - columns WE FIND D1
n1=size(D1,1) %number of record belongs to classification
sampleSpace = size(search,1) %sample space of the priop probability(#of c1 + #of c2 .... cn)
pc1 = n1/sampleSpace %prior probability of the n
mu1 = mean(D1) %mean of D1
Z1 = D1 - mu1 % centered data of D1
Eps1 = (1/n1)*(transpose(Z1)*Z1) %covariance matrix if Z1
numOfClassifier = numOfClassifier + 1;
if search(:,c) ~= numOfClassifier
break
end
end
end
I need to return
D1
Eps1
I want to return the entire values of for loop but I only end up with values from the last row.
You can store the iteration results in a cell array, and return the cell array:
Function returning two cell arrays (I named them allD1 and allEps1):
function [allD1, allEps1] = findD(i,j,c,search)
Initialize the cell arrays to empty cells before the loop:
allD1 = {};
allEps1 = {};
Add D1 and Eps1 to the end of the cell arrays (place it before the line with the break statement):
allD1{end + 1} = D1;
allEps1{end + 1} = Eps1;
Here is the modified code:
i=input('Enter a start row: ');
j=input('Enter a end row: ');
c=input('Enter classifier variable column number:')
search= importfiledataset('search-queries-features.csv',i,j);
[n,p]=size(search);
if j>n
disp('Please enter a smaller number!');
end
[D1,Eps1]=findD(i,j,c,search);
disp(D1);
disp(n1);
function [allD1, allEps1] = findD(i,j,c,search) %Find D vlaues with for loop for each classification value
%Initialize empty cell arrays
allD1 = {};
allEps1 = {};
for numOfClassifier = 1 : 100
a = search(search(:,c)==numOfClassifier,:) ;
q1 = a(all(~isnan(a),2),:); % for nan - rows
D1 = a(:,all(~isnan(a))) % for nan - columns WE FIND D1
n1=size(D1,1) %number of record belongs to classification
sampleSpace = size(search,1) %sample space of the priop probability(#of c1 + #of c2 .... cn)
pc1 = n1/sampleSpace %prior probability of the n
mu1 = mean(D1) %mean of D1
Z1 = D1 - mu1 % centered data of D1
Eps1 = (1/n1)*(transpose(Z1)*Z1) %covariance matrix if Z1
%Add D1 (and Eps1) to the end of the cell array
allD1{end + 1} = D1;
allEps1{end + 1} = Eps1;
numOfClassifier = numOfClassifier + 1;
if search(:,c) ~= numOfClassifier
break
end
end
end
Cell arrays are more general then arrays - cells can store values of different types and shapes, opposed to arrays where all elements must be of the same type.
In your case, multi-dimensional arrays might fit, but it's more confusing.
With cell arrays, each cell holds the result of the matching iteration.
For example: allD1{3} holds the value of D1 in the third iteration.

Vectorize the sum of outer products of coresponding columns of two matrices using Matlab/Octave

Suppose I have two matrices A and B which are made up of column vectors as follows.
A = [a_1,a_2,...,a_N];
B = [b_1,b_2,...,b_N];
Is there any way to vectorize the calculation of the sum of outer products for every column in A with the corresponding column in B. Here is my non-vectorized solution.
S = zeros(size(A,1), size(B,1));
for n=1:N
S = S + A(:,n)*B(:,n)'; % S = S + a_n * b_n'
end
Any help would be greatly appreciated.
you are not clear on what N is, but I assume that N = number of column vectors - which means you are simply doing A * B'
A = rand(3,4);
B = rand(3,4);
N = size(A,2);
S = zeros(size(A,1), size(B,1));
for n=1:N
S = S + A(:,n)*B(:,n)'; % S = S + a_n * b_n'
end
%Check that you are doing A*B'
S == A*B'
>> ans =
1 1 1
1 1 1
1 1 1

Exclude value by the calculation

I have an array A (I have written so as to make it similar to the matrix that I am using) :
%%%%%%%%%%%%% This is Matrix %%%%%%%%%%%%%%%%%%%%
a = 3; b = 240; c = 10; d = 30; e = 1;
mtx1 = a.*rand(30,1) + a;
mtx2 = round((b-c).*rand(30,1));
mtx3 = round((d-e).*rand(30,1));
mtx4 = -9999.*ones(30,1);
A = [mtx1 mtx2 mtx3 mtx4];
for i = 10:12
for ii = 17 :19
A(i,:)= -9999;
A(ii,:)= 999;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
I would calculate some statistical values, excluding from the calculation the values **-9999 and 999.
the statistical values must be calculated with respect to each column.
the columns represent respectively: the wind speed, direction, and
other parameters
I wrote a code but it is not correct
[nr,ncc]=size(A);
for i=1:ncc
B = A(:,i); %// Temp Vector
Oup=1; Odw=1; %// for Vector Control
while Oup>0 %// || Odw>0 % Oup>0 OR Odw>0 , Oup>0 && (AND) Odw>0
B=sort(B,'descend');
U = find(B<999 & B>-9999); % find for each column of the temp
%vector
Oup = length(U); % Calculates the length
B(U)=[]; % Delete values -9999 and 9999
end
% calculates parameters with the vector temp
count(i)=length(B);
med(i)=mean(B);
devst(i)=std(B);
mediana(i)=median(B);
vari(i)=var(B);
kurt(i)=kurtosis(B);
Asimm(i)=skewness(B);
Interv(i)=range(B);
Mass(i)=max(B);
Mini(i)=min(B);
if length(B)<nr
B(length(B)+1:nr)=nan;
end
C(:,i)=B(:); %//reconstruction of the original matrix
end
would you have any suggestions?
If your data set is in A, and you want to operate on it with a function f, just use logical indexing, i.e.:
f(A( ~(A==999 & A==-9999) )) =...
Alternatively, use find and linear indexing:
ind = find( ~(A==999 & A==-9999) );
f(A(ind)) = ....

How to oppositely order two vectors in Matlab?

I have the code below for oppositely ordering two vectors. It works, but I want to specify the line
B_diff(i) = B(i) - B(i+1);
to hold true not just for only
B_diff(i) = B(i) - B(i+1); but for
B_diff(i) = B(i) - B(i+k); where k can be any integer less than or equal to n. The same applies to "A". Any clues as to how I can achieve this in the program?
For example, I want to rearrange the first column of the matrix
A =
1 4
6 9
3 8
4 2
such that, the condition should hold true not only for
(a11-a12)(a21-a22)<=0;
but also for all
(a11-a13)(a21-a23)<=0;
(a11-a14)(a21-a24)<=0;
(a12-a13)(a22-a23)<=0;
(a12-a14)(a22-a24)<=0; and
(a13-a14)(a23-a24)<=0;
## MATLAB CODE ##
A = xlsread('column 1');
B = xlsread('column 2');
n = numel(A);
B_diff = zeros(n-1,1); %Vector to contain the differences between the elements of B
count_pos = 0; %To count the number of positive entries in B_diff
for i = 1:n-1
B_diff(i) = B(i) - B(i+1);
if B_diff(i) > 0
count_pos = count_pos + 1;
end
end
A_desc = sort(A,'descend'); %Sort the vector A in descending order
if count_pos > 0 %If B_diff contains positive entries, divide A_desc into two vectors
A_less = A_desc(count_pos+1:n);
A_great = sort(A_desc(1:count_pos),'ascend');
A_new = zeros(n,1); %To contain the sorted elements of A
else
A_new = A_desc; %This is then the sorted elements of A
end
if count_pos > 0
A_new(1) = A_less(1);
j = 2; %To keep track of the index for A_less
k = 1; %To keep track of the index for A_great
for i = 1:n-1
if B_diff(i) <= 0
A_new(i+1) = A_less(j);
j = j + 1;
else
A_new(i+1) = A_great(k);
k = k + 1;
end
end
end
A_diff = zeros(n-1,1);
for i = 1:n-1
A_diff(i) = A_new(i) - A_new(i+1);
end
diff = [A_diff B_diff]
prod = A_diff.*B_diff
The following code orders the first column of A opposite to the order of the second column.
A= [1 4; 6 9; 3 8; 4 2]; % sample matrix
[~,ix]=sort(A(:,2)); % ix is the sorting permutation of A(:,2)
inverse=zeros(size(ix));
inverse(ix) = numel(ix):-1:1; % the un-sorting permutation, reversed
B = sort(A(:,1)); % sort the first column
A(:,1)=B(inverse); % permute the first column according to inverse
Result:
A =
4 4
1 9
3 8
6 2

Replace the diagonal of matrix

I am interesting to replace the diagonal of matrix D to 1,2,3,4.
This is matrix D:
A=[1,2,3,4,2,3,4,5; 3,4,5,6,4,5,6,7];
D=[A;A];
D=[D D]; % size of matrix [4x16] %
To set the main diagonal to integers starting a 1 and incrementing by 1:
D(eye(4)==1) = 1:4
Or to generalize it:
n = min(size(D));
D(eye(n)==1) = 1:n;
note here that the ==1 is to convert the output of eye(n), the identity matrix, to type logical.
EDIT:
This is just a guess at what you mean by all the diagonals but here goes:
n = size(D,1);
m = size(D,2);
I = repmat(eye(min([n,m])), ceil(n/m), ceil(m/n));
I = I(1:n, 1:m)==1
d = repmat(1:min([n,m]), 1, max([ceil(n/m), ceil(m/n)]));
d = d(1:max(m,n));
D(I) = d