multiplying large matrix elements results in infinite - matlab

I am supposed to combine all the matrix into one, which concatenate horizontally by
matrix = [matrix1 matrix2 matrix3];
now i have to find the mean of the matrix which is 32 x 2039 dimensions.
i tried looping through each row and using mean for the whole elements in that row multipled and divided by the number of elements which is 2039.
answer i get is -Inf, all the time.
help would be appreciated.
thanks
my code what i could remember in case
[r, c] = size(matrix);
for i = 1:r
rowvalues = matrix(i,[1:c]);
mean(i,1) = mean2(rowvalues); %or mean(rowvalues,2);
end
results in -Inf.
my aim is to calculate the mean of the matrix which should be 39 X 1 dimensions.
thanks

When an element of a row is -Inf, the whole row will have a mean=-Inf.
I suggest you check this with the following code:
% The indices of the occurences of -Inf in matrix
mInfIndices=(matrix==-Inf);
% Does the row contain an -Inf?
mInfInRows=sum(mInfIndices,2)>0;
disp(mInfInRows);
This way you will see which rows contain a -Inf.

Related

Median for every nth values in Matlab

I don't have much experience with Matlab.
I have a row vector with 17497 elements and I would like to create a loop to get the median of every 120 values.
So, the median of value 1:120, then the next median of values 121:240 and so on.
Could somebody help me?
Thanks in advance,
Sunna
You could use accumarray
N = 17497;
data = rand(N,1);
%# array with 1,1,1,2,2,2 etc
idx = floor((0:N-1).'/120)+1;
%# create median for groups of 120 data points
%# discard the last one if needed as it's <120 points
out = accumarray(idx,data,[],#median);
I am going to assume that you simply ignore the last few elements in your row vector such that the row can be equally divided into parts of 120. You can then transform your row vector into a 120 row matrix. median can operate on this matrix directly and return the median of each column.
N = 17497;
A = randn(1,N);
newN = N - mod(N,120);
median(reshape(A(1:newN),120,[]));

Vector and matrix comparison in MATLAB

I have vector with 5 numbers in it, and a matrix of size 6000x20, so every row has 20 numbers. I want to count how many of the 6000 rows contain all values from the vector.
As the vector is a part of a matrix which has 80'000'000 rows, each containing unique combinations, I want a fast solution (which doesn't take more than 2 days).
Thanks
With the sizes you have, a bsxfun-based approach that builds an intermediate 6000x20x5 3D-array is affordable:
v = randi(9,1,5); %// example vector
M = randi(9,6000,20); %// example matrix
t = bsxfun(#eq, M, reshape(v,1,1,[]));
result = sum(all(any(t,2),3));

Initializing a matrix with a certain value in matlab

I have this matrix A of size 100x100. Now I have another vector Z=(1,24,5,80...) which has 100 elements. it is a column vector with 100 elements. Now for each row of the matrix A, I want its A(i,j) element to be 1 where i is the row from 1:100 and j is the column which is given by Z
So the elements that should be 1 should be
1,1
2,24
3,5
4,80
and so on
I know I can do it using a loop. But is there a direct simple way I mean one liner?
A matrix that has 100 non-zero elements out of 10000 (so only 1% non-zero) in total is best stored as sparse. Use the capability of matlab.
A = sparse(1:100,Z,1,100,100);
This is a nice, clean one-linear, that results in a matrix that will be stored more efficiently that a full matrix. It can still be used for matrix multiplies, and will be more efficient at that too. For example...
Z = randperm(100);
A = sparse(1:100,Z,1,100,100);
whos A
Name Size Bytes Class Attributes
A 100x100 2408 double sparse
This is a reduction in memory of almost 40 to 1. And, while the matrix is actually rather small as these things go, it is still faster to use it as sparse.
B = rand(100);
timeit(#() B*A)
ans =
4.5717e-05
Af = full(A);
timeit(#() B*Af)
ans =
7.4452e-05
Had A been 1000x1000, the savings would have been even more significant.
If your goal is a full matrix, then you can use full to convert it to a full matrix, or accumarray is an option. And if you want to insert values into an existing array, then use sub2ind.
One way to do it is to convert the values in Z to absolute indices in A using sub2ind, and then use vector indexing:
idx = sub2ind(size(A), 1:numel(Z), Z);
A(idx) = 1;
or simply in a one-liner:
A(sub2ind(size(A), 1:numel(Z), Z)) = 1;

How to select values with the higher occurences from several matrices having the same size in matlab?

I would like to have a program that makes the following actions:
Read several matrices having the same size (1126x1440 double)
Select the most occuring value in each cell (same i,j of the matrices)
write this value in an output matrix having the same size 1126x1440 in the corresponding i,j position, so that this output matrix will have in each cell the most occurent value from the same position of all the input matrices.
Building on #angainor 's answer, I think there is a simpler method using the mode function.
nmatrices - number of matrices
n, m - dimensions of a single matrix
maxval - maximum value of an entry (99)
First organize data into a 3-D matrix with dimensions [n X m X nmatrices]. As an example, we can just generate the following random data in a 3-D form:
CC = round(rand(n, m, nmatrices)*maxval);
and then the computation of the most frequent values is one line:
B = mode(CC,3); %compute the mode along the 3rd dimension
Here is the code you need. I have introduced a number of constants:
nmatrices - number of matrices
n, m - dimensions of a single matrix
maxval - maximum value of an entry (99)
I first generate example matrices with rand. Matrices are changed to vectors and concatenated in the CC matrix. Hence, the dimensions of CC are [m*n, nmatrices]. Every row of CC holds individual (i,j) values for all matrices - those you want to analyze.
CC = [];
% concatenate all matrices into CC
for i=1:nmatrices
% generate some example matrices
% A = round(rand(m, n)*maxval);
A = eval(['neurone' num2str(i)]);
% flatten matrix to a vector, concatenate vectors
CC = [CC A(:)];
end
Now we do the real work. I have to transpose CC, because matlab works on column-based matrices, so I want to analyze individual columns of CC, not rows. Next, using histc I find the most frequently occuring values in every column of CC, i.e. in (i,j) entries of all matrices. histc counts the values that fall into given bins (in your case - 1:maxval) in every column of CC.
% CC is of dimension [nmatrices, m*n]
% transpose it for better histc and sort performance
CC = CC';
% count values from 1 to maxval in every column of CC
counts = histc(CC, 1:maxval);
counts have dimensions [maxval, m*n] - for every (i,j) of your original matrices you know the number of times a given value from 1:maxval is represented. The last thing to do now is to sort the counts and find out, which is the most frequently occuring one. I do not need the sorted counts, I need the permutation that will tell me, which entry from counts has the highest value. That is exactly what you want to find out.
% sort the counts. Last row of the permutation will tell us,
% which entry is most frequently found in columns of CC
[~,perm] = sort(counts);
% the result is a reshaped last row of the permutation
B = reshape(perm(end,:)', m, n);
B is what you want.

2d matrix histogram in matlab that interprets each column as a separate element

I have a 128 x 100 matrix in matlab, where each column should be treated as a separate element. Lets call this matrix M.
I have another 128 x 2000 matrix(called V) composed of columns from matrix M.
How would I make a histogram that maps the frequency of each column being used in the second matrix?
hist(double(V),double(M)) gives the error:
Error using histc
Edge vector must be monotonically
non-decreasing.
what should I be doing?
Here is an example. We start with data that resembles what you described
%# a matrix of 100 columns
M = rand(128,100);
sz = size(M);
%# a matrix composed of randomly selected columns of M (with replacement)
V = M(:,randi([1 sz(2)],[1 2000]));
Then:
%# map the columns to indices starting at 1
[~,~,idx] = unique([M,V]', 'rows', 'stable');
idx = idx(sz(2)+1:end);
%# count how many times each column occurs
count = histc(idx, 1:sz(2));
%# plot histogram
bar(1:sz(2), count, 'histc')
xlabel('column index'), ylabel('frequency')
set(gca, 'XLim',[1 sz(2)])
[Lia,Locb] = ismember(A,B,'rows') also returns a vector, Locb,
containing the highest index in B for each row in A that is also a row
in B. The output vector, Locb, contains 0 wherever A is not a row of
B.
ismember with the rows argument can identify which row of one matrix the rows of another matrix come from. Since it works on rows, and you are looking for columns, just transpose both matrices.
[~,Locb]=ismember(V',M');
histc(Locb)