I am trying to do sparse matrix addition in matlab.
1. Suppose two matrix are give A and B, we have to get the sparse matrix format of the given matrix. This is easily done by sparse function in matlab and categorized accordingly in row, col and val.
2. Now we check the rows and cols of two sparse matrix and add the val if they are equal. If they are not equal just push it to output instead of adding them.
This is the code part which i have done so far :
function sparse()
A=[1 0 3;5 2 0;5 2 4];
B=[1 3 0;2 0 0;1 2 3];
A1=sparse(A);
B1=sparse(B);
[row1,col1,val1]=find(A1);
[row2,col2,val2]=find(B1);
A2=[row1,col1,val1];
B2=[row2,col2,val2];
for i=1:size(A2,1)
for j=1:size(B2,1)
if row1(i)==row2(j) && col1(i)==col2(j)
C=val1(i)+val2(j)
end
end
end
end
Help much appreciated.
1. Suppose two matrix are give A and B, we have to get the sparse matrix format of the given matrix. This is easily done by sparse function in matlab and categorized accordingly in row, col and val.
2. Now we check the rows and cols of two sparse matrix and add the val if they are equal. If they are not equal just push it to output instead of adding them.
This is the code part which i have done so far :
function sparse()
A=[1 0 3;5 2 0;5 2 4];
B=[1 3 0;2 0 0;1 2 3];
A1=sparse(A);
B1=sparse(B);
[row1,col1,val1]=find(A1);
[row2,col2,val2]=find(B1);
A2=[row1,col1,val1];
B2=[row2,col2,val2];
for i=1:size(A2,1)
for j=1:size(B2,1)
if row1(i)==row2(j) && col1(i)==col2(j)
C=val1(i)+val2(j)
end
end
end
end
Help much appreciated.