Matrix operation difficulty - matlab

I am having trouble in pushing back a vector into a matrix. Considering, N×N matrix called MyMatrix, where N = 10 which consists of zero and non-zero elements with the diagonal elements being all zero. There are 2 vectors: Positive_Vector of dimension 15 that consists of 10 non-zero elements extracted from MyMatrix and ConceptsVector consisting of N elements respectively. Suppose the vector consists of the follwing elements
Positive_Vector = [MyMatrix(1,2), MyMatrix(1,6), MyMatrix(2,5), MyMatrix(2,6), MyMatrix(2,10), MyMatrix(3,1), MyMatrix(4,10), MyMatrix(5,3), MyMatrix(5,9),MyMatrix(6,1),MyMatrix(6,7),MyMatrix(7,3),MyMatrix(7,4),MyMatrix(8,1),MyMatrix(8,3)];
Concepts = [0.6,0.1,0.0,0.2,0.8,0.33,0.21,0.5,0.11];
My problem is how can I update MyMatrix with a new vector New_Positive_vector consisting of the same dimension but different values of the elements, such that the following operation
C1 = Concepts*NewMyMatrix
can be performed?
This is how I extracted the Positive_Vector. Can somebody please show how to do the reverse ie push back the new elements of New_Positive_Vector into the the respective places in NewMyMatrix?
for ii = 1:10
for jj = 1:10
if (MyMatrix(ii,jj)~=0)
Positive_Vector = MyMatrix(ii,jj);
end
end
end

Your explanation is vague but I assume that you want to extract the non-zero (or positive) elements from a matrix, do some operations in these elements, and push back them into the original matrix. Then I suggest,
MyMatrix = (rand(5)>0.5).*rand(5);
[n,m,Positive_vector] = find(MyMatrix);
k = sub2ind(size(MyMatrix),n,m);
MyMatrix(k) = Positive_vector*2;
First line is for generating a random matrix with some zeros. Second line is to find the non-zero element of the matrix. If you just want the positive element, then you can modify it to find(MyMatrix > 0). Here, n and m are the sets of row and column numbers of non-zero elements, but I make that into a 1D indices in the third line. Fourth line is to apply some operation (this case multiply by 2) to the extracted vector and push back to the original places in the original matrix.
I assume that you do more complicated operation than multiplying the non-zero elements by 2. Otherwise you can do something like this...
MyMatrix = MyMatrix - (MyMatrix>0).*MyMatrix + (MyMatrix>0).*(MyMatrix)*2

Here is just a slightly simpler way of doing what ysakamoto does:
%// some test matrix
MyMatrix = (rand(5)>0.5).*rand(5);
%// Logical indices to the non-zero entries
inds = MyMatrix ~= 0;
%// Do operations on the non-zeros, and assign results back
MyMatrix(inds) = 2*MyMatrix(inds);

If I understand you correctly then you should do the following:
First of all, with the code you have provided for generating PositiveVector, you will get a single element and not a vector. I assume you want to generate it as follows:
[nonZeroRows,nonZeroCols]=find(MyMatrix~=0);
Positive_Vector=MyMatrix(sub2ind(size(MyMatrix),nonZeroRows,nonCols));
Suppose now you have a New_Positive_Vector which you want to insert into NewMyMatrix, you do it as follows:
NewMyMatrix=zeros(size(MyMatrix));
NewMyMatrix(sub2ind(size(NewMyMatrix),nonZeroRows,nonZeroCols))=`New_Positive_Vector`;

Related

Simplify how to find unique rows of a Matlab array

I would like your help to vectorise (or, more generally, make more efficient) a Matlab code where:
Step 1: I construct a matrix C of size sgxR, where each row contains a sequence of ones and zeros, according to whether certain logical conditions are satisfied.
Step 2: I identify the indices of the unique rows of C.
I now describe the code in more details.
Step 1: Creation of the matrix C. I divide this step in 3 sub-steps.
Step 1.a: Create the 1x3 cell U_grid. For j=1,2,3, U_grid{j} is a sg x K matrix of numbers.
clear
rng default
n_U_sets=3; %This parameter will not be changed
sg=4; %sg is usually quite large, for instance 10^6
K=5; %This parameter can range between 3 and 8
Ugrid=cell(n_U_sets,1);
for j=1:n_U_sets
Ugrid{j}=randn(sg,K);
end
Step 1.b: For each g=1,...,sg
Take the 3 rows Ugrid{1}(g,:), Ugrid{2}(g,:), Ugrid{3}(g,:).
Take all possible 1x3 rows that can be formed such that the first element is from Ugrid{1}(g,:), the second element is from
Ugrid{2}(g,:), and the third element is from Ugrid{3}(g,:). There are K^3 such rows.
Create the matrix D{g} storing row-wise all possible pairs of such 1x3 rows. D{g} will have size (K^3*(K^3-1)/2)x6
This is coded as:
%Row indices of all possible pairs of rows
[y, x] = find(tril(logical(ones(K^(n_U_sets))), -1));
indices_pairs = [x, y]; %K^3*(K^3-1)/2
%Create D{g}
for g=1:sg
vectors = cellfun(#(x) {x(g,:)}, Ugrid); %1x3
T_temp = cell(1,n_U_sets);
[T_temp{:}] = ndgrid(vectors{:});
T_temp = cat(n_U_sets+1, T_temp{:});
T = reshape(T_temp,[],n_U_sets);
D{g}=[T(indices_pairs(:,1),:) T(indices_pairs(:,2),:)]; %(K^3*(K^3-1)/2) x (6)
end
Step 1.c: From D create C. Let R=(K^3*(K^3-1)/2). R is the size of any D{g}. C is a sg x R matrix constructed as follows: for g=1,...,sg and for r=1,...,R
if D{g}(r,1)>=D{g}(r,5)+D{g}(r,6) or D{g}(r,4)<=D{g}(r,2)+D{g}(r,3)
then C(g,r)=1
otherwise C(g,r)=0
This is coded as:
R=(K^(n_U_sets)*(K^(n_U_sets)-1)/2);
C=zeros(sg,R);
for g=1:sg
for r=1:R
if D{g}(r,1)>=D{g}(r,5)+D{g}(r,6) || D{g}(r,4)<=D{g}(r,2)+D{g}(r,3)
C(g,r)=1;
end
end
end
Step 2: Assign the same index to any two rows of C that are equal.
[~,~,idx] = unique(C,"rows");
Question: Steps 1.b and 1.c are the critical ones. With sg large and K between 3 and 8, they take a lot of time, due to the loop and reshape. Do you see any way to simplify them, for instance by vectorising?

Performed a smoothing function on a matrix, but now only matching indices give values

I have a matrix 1000x1000x50 and I performed a function on each vector along the third dimension in a loop (1,000,000 vectors, 50 elements long). When I try to view any specific element where m=n, i.e. (1000,1000,40) , a nonzero value is displayed. However, when I try to view an element where m =/= n, i.e. (1000,1001,40), only a 0 is returned. I know that (1001,1001,40) has a nonzero value, and I know that the original matrix had a nonzero element at (1000,1001,40).
Here's the loop I used:
mymatrix_new = zeros(size(mymatrix));
for i=1:length(mymatrix)
mymatrix_new(i,i,:) = wdenoise(squeeze(mymatrix(i,i,:)));
end
For the values that DO display, the result is what I expected- a smoothed signal. I just don't understand why certain elements that are nonzero are displaying as zero when the m and n indices are't identical.
You are iterating and updating only the cells that have m == n. This happens because you use a single for loop. All other values are not visited and are never updated, this is why they remain zero.
If you look at your foor loop:
for i=1:length(mymatrix)
In the first iteration i = 1 and it will update:
mymatrix_new(1,1,:) = wdenoise(squeeze(mymatrix(1,1,:)));
In the second iteration i = 2 and it will update:
mymatrix_new(2,2,:) = wdenoise(squeeze(mymatrix(2,2,:)));
As you can see, you never update mymatrix_new(1, 2) or any cell other than the ones that have m == n == i
You need to use two nested for loops, such that you update all combinations of i and j
mymatrix_new = zeros(size(mymatrix));
for i=1:length(mymatrix)
for j=1:length(mymatrix) % Here it assumes the matrix is a square
mymatrix_new(i,j,:) = wdenoise(squeeze(mymatrix(i,j,:)));
end
end

Mean value of each column of a matrix

I have a 64 X 64 matrix that I need to find the column-wise mean values for.
However, instead of dividing by the total number of elements in each column (i.e. 64), I need to divide by the total number of non-zeros in the matrix.
I managed to get it to work for a single column as shown below. For reference, the function that generates my matrix is titled fmu2(i,j).
q = 0;
for i = 1:64
if fmu2(i,1) ~= 0;
q = q + 1;
end
end
for i = 1:64
mv = (1/q).*sum(fmu2(i,1));
end
This works for generating the "mean" value of the first column. However, I'm having trouble looping this procedure so that I will get the mean for each column. I tried doing a nested for loop, but it just calculated the mean for the entire 64 X 64 matrix instead of one column at a time. Here's what I tried:
q = 0;
for i = 1:64
for j = 1:64
if fmu2(i,j) ~= 0;
q = q +1;
end
end
end
for i = 1:64
for j = 1:64
mv = (1/q).*sum(fmu2(i,j));
end
end
Like I said, this just gave me one value for the entire matrix instead of 64 individual "means" for each column. Any help would be appreciated.
For one thing, do not call the function that generates your matrix in each iteration of a loop. This is extremely inefficient and will cause major problems if your function is complex enough to have side effects. Store the return value in a variable once, and refer to that variable from then on.
Secondly, you do not need any loops here at all. The total number of nonzeros is given by the nnz function (short for number of non-zeros). The sum function accepts an optional dimension argument, so you can just tell it to sum along the columns instead of along the rows or the whole matrix.
m = fmu2(i,1)
averages = sum(m, 1) / nnz(m)
averages will be a 64-element array with an average for each column, since sum(m, 1) is a 64 element sum along each column and nnz(m) is a scalar.
One of the great things about MATLAB is that it provides vectorized implementations of just about everything. If you do it right, you should almost never have to use an explicit loop to do any mathematical operations at all.
If you want the column-wise mean of non-zero elements you can do the following
m = randi([0,5], 5, 5); % some data
avg = sum(m,1) ./ sum(m~=0,1);
This is a column-wise sum of values, divided by the column-wise number of elements not equal to 0. The result is a row vector where each element is the average of the corresponding column in m.
Note this is very flexible, you could use any condition in place of ~=0.

matlab Create growing matrix with for loop that grows by 3 per loop

So I have written this:
HSRXdistpR = squeeze(comDatape_m1(2,7,1,:,isubj));
HSRXdistpL = squeeze(comDatape_m1(2,4,1,:,isubj));
TocomXdistp = squeeze(comDatape_m1(2,10,1,:,isubj));
for i = 1:2;
HSRXp = NaN(8,3*i);
HSRXp(:,i*3) = [HSRXdistpR(:,i) HSRXdistpL(:,i) TocomXdistp(:,i)];
end
In the first part I am just selecting data from a 5-D matrix, nothing special. All that's important here is that it creates an 8x2 matrix per line (isubj=2). Now I want to add the first column of each matrix into an 8x3 matrix, and then the second column of each matrix into the same matrix (creating an 8x6 matrix). Since the number of my subjects will vary, I want to do this in a for loop. This way, if the isubj increases to 3, it should go on to create an 8x9 matrix.
So I tried to create a matrix that will grow by 3 for each iteration of i, which selects the ith column of each of the 3 matrices and then puts them in there.
However I get the following error:
Subscripted assignment dimension mismatch.
Is it possible to let a matrix grow by more than one in a for loop? Or how should it be done otherwise?
Here is your problem:
HSRXp(:,i*3) = [HSRXdistpR(:,i) HSRXdistpL(:,i) TocomXdistp(:,i)];
You're trying to assign an n x 3 matrix (RHS) into an n x 1 vector (LHS). It would be easier to simply use horizontal concatenation:
HSRXp = [HSRXp, [HSRXdistpR(:,i) HSRXdistpL(:,i) TocomXdistp(:,i)]];
But that would mean reallocation at each step, which might slow your code down if the matrix becomes large.

replace all numbers in a matrix

There are two matrices; the first one is my input matrix
and the second one ("renaming matrix") is used to replace the values of the first one
That is, looking at the renaming matrix; 701 must be replaced by 1,...,717 must be replaced by 10,etc.. such that the input matrix becomes as such
The ? values are defined but i didn't put them. The second column of the input matrix is already sorted(ascending order from top down) but the values are not consecutive(no "710": see first pic).
The question is how to get the output matrix(last pic) from the first two.
Looks to me like it's screaming for a sparse matrix solution. In matlab you can create a sparse matrix with the following command:
SM = sparse( ri, ci, val );
where ri is the row index of the non-zero elements, ci is the corresponding column index, and val is the values.
Let's call your input matrix IM and your lookup matrix LUM, then we construct the sparse matrix:
nr = size(LUM, 1);
SM = sparse( ones(nr, 1), LUM(:, 1), LUM(:, 2) );
Now we can get your result in a single line:
newMatrix = reshape(SM(1, IM), size(IM));
almost magic.
I didn't have a chance to check this tonight - but if it doesn't work exactly as described, it should be really really close...
If the values in the first column all appear in the second column, and if all you want is replace the values in the second column by 1..n and change the values in the first column accordingly, you can do all of this with a simple call to ismember:
%# define "inputMatrix" here as the first array in your post
[~,newFirstColumn] = ismember(inputMatrix(:,1),inputMatrix(:,2));
To create your output, you'd then write
outputMatrix = [newFirstColumn,(1:length(newFirstColumn))'];
If M is the original matrix and R is the renaming matrix, here's how you do it
N = M;
for n = 1:size(M,1)
N(find(M==R(n,1))) = R(n,2);
end
Note that in this case you're creating a new matrix N with the renamed values. You don't have to do that if you like.