How to add a row to a sparse matrix in itpp - matlab

In matlab we write :
H2= H(p==1,:)
where H2 and H are sparse double matrix and p is a logical vector.
how I can write it in itpp?

Not 100% familiar with itpp, but I would try something like
int h = 0, w = H.cols();
// count number of set elements in p to get number of rows of H2
for ( int i = 0 ; i < p.length() ; i++ ) {
h += (p[i] == 1);
}
// alocate H2
H2 = Sparse_Mat( h, w, H.nnz() ); // estimate number of nonzeros in H2
// copy the relevant elements
for ( int i = 0, i2 = 0 ; i < p.length() && i2 < h ; i++ ) {
if ( p[i] != 1 ) {
continue;
}
H2.set_submatrix( i2, 0, H.get_submatrix( i, i+1, 0, w ).full() );
i2++;
}
Clearly, working with sparse columns is much easier using get_col and set_col, so you might consider transposing H first and then perform the operation returning H2.transpose().

Related

Image Transformation Without Loop

I am writing image transformation function in matlab instead of using predefined functions like 'imwarp or imtransform'. I am done with writing the code roughly but it is taking too long due to the use of loop.
Please suggest me a solution which can achieve the same result without loops
function I2 = f_transform(A, I1)
%A is an affine transformation matrix
%I1 is original image to be transformed
s=size(A);
if(s(1)~=3 || s(2)~=3)
disp("Invalid Transforming Matrix");
I2=0;
return;
end
if(det(A)==0)
disp("The given Transforming Matrix is Singular");
I2=0;
return;
end
[r, c]=size(I1);
extremeValues = [1 1 r r ; 1 c 1 c; 1 1 1 1];
newExtremeValues = A * extremeValues;
minRow = floor( min( newExtremeValues(1,:) ) );
maxRow = ceil( max( newExtremeValues(1,:) ) );
minCol = floor( min( newExtremeValues(2,:) ) );
maxCol = ceil( max( newExtremeValues(2,:) ) );
I2 = zeros(maxRow - minRow + 1, maxCol - minCol + 1);
for i = minRow:maxRow
for j=minCol:maxCol
b = A \ [i j 1]';
p = b(1) / b(3);
q = b(2) / b(3);
if(p >= 1 && p <= r && q >= 1 && q <= c)
I2(i - minRow + 1, j - minCol + 1) = I1(round(p),round(q));
end
end
end
I2 = uint8(I2);
return;
end

Advanced Encryption Standard (AES) polynomial multiplication in octave / matlab

I am trying to perform polynomial multiplication as explained in the Advanced Encryption Standard (AES) draft.
Here's what I have so far:
function y = multiply_x2( a )
% a is a 1 x 8 binary vector
% y is a 1 x 8 binary vector
% t is a 1 x 8 binary vector corresponding to the "AES irreducible polynomial"
y = [ a(2:8) 0 ]; % Multiply byte 'a' by 2 using "left shift"
t = [ 0 0 0 a(1) a(1) 0 a(1) a(1) ]; % 't' only becomes the "AES irreducible
% polynomial" if a(1) == 1, otherwise
% it becomes the "zero" byte array
y = mod( y + t , 2 ) ; % XOR operation on y and t, as described in AES.
end
The code above is for
"y = {02} . a"
(where "{}" denotes hexadecimal notation, whose binary representation can be interpreted as the presense of the respective power of x in a polynomial. For example, {02} corresponds to 00000010, which corresponds to the polynomial "x", {06} would correspond to "x2+x", etc, as per the AES docs)
I want to multiply a with 0e , 09 , 0d, and 0b.
How will the code be for each of them? i.e. for:
"y= ( {0e} . a )"
"y= ( {09} . a )"
"y= ( {0d} . a )"
"y= ( {02} . a )"
This was an interesting problem. Here is a general solution for multiplication as defined in the AES doc you linked. I use the name xtime for the {02} multiplication, and I implement "addition" (xadd) as an XOR operation (i.e. !=) directly, since this is easier.
Helper functions:
%% in file isByte.m
function Out = isByte (a)
a = a(:).'; % ensure horizontal vector representation
if all (a == 0 | a == 1) && length (a) == 8; Out = true; return; end
Out = false;
end
%% in file byte2hex.m
function Out = byte2hex (a)
a = a(:).'; % ensure horizontal vector
assert (isByte (a), 'Input needs to be a valid "byte" array');
Out = sum (a .* ([2,2,2,2,2,2,2,2] .^ [7:-1:0])); Out = dec2hex (Out);
end
%% in file hex2byte.m
function Out = hex2byte (h)
assert (isxdigit (h) && hex2dec (h) < 256, 'Input needs to be a valid hex number below FF');
Out = dec2bin (hex2dec (h)); Out = sprintf ('%8s', Out);
Out = Out - 48 ; Out(Out == -16) = 0; % convert spaces to zeros
end
Polynomial functions:
%% in file xadd.m
function Out = xadd (a, b)
a = a(:).'; b = b(:).'; % ensure horizontal vector representations
assert (isByte (a) && isByte (b), 'Inputs need to be valid "byte" arrays');
Out = a != b;
end
%% in file xtime.m
function Out = xtime (a)
a = a(:).'; % ensure horizontal vector
assert (isByte (a), 'Input needs to be a valid "byte" array');
Out = [a(2 : 8), 0]; % left shift
if a(1) == 1
Out = xadd (Out, [0, 0, 0, 1, 1, 0, 1, 1]); % subtract (= add) the AES m(x) polynomial
end
end
% in file xmultiply.m
function Out = xmultiply (a, b)
a = a(:)'; b = b(:)'; % ensure horizontal vector representations
assert (isByte(a) && isByte(b), 'Inputs need to be valid "byte" arrays');
Out = [0,0,0,0,0,0,0,0];
if a == [0, 0, 0, 0, 0, 0, 0, 0] || b == [ 0, 0, 0, 0, 0, 0, 0, 0]; return; end
if b(8) == 1; Out = xadd (Out, a); end % yes this could be done recursively but, why bother.
if b(7) == 1; Out = xadd (Out, xtime (a)); end
if b(6) == 1; Out = xadd (Out, xtime (xtime (a))); end
if b(5) == 1; Out = xadd (Out, xtime (xtime (xtime (a)))); end
if b(4) == 1; Out = xadd (Out, xtime (xtime (xtime (xtime (a))))); end
if b(3) == 1; Out = xadd (Out, xtime (xtime (xtime (xtime (xtime (a)))))); end
if b(2) == 1; Out = xadd (Out, xtime (xtime (xtime (xtime (xtime (xtime (a))))))); end
if b(1) == 1; Out = xadd (Out, xtime (xtime (xtime (xtime (xtime (xtime (xtime (a)))))))); end
end
Example use: (same example as in the AES doc)
octave:1> a = hex2byte("57")
a =
0 1 0 1 0 1 1 1
octave:2> b = hex2byte("13")
b =
0 0 0 1 0 0 1 1
octave:3> c = xmultiply(a, b)
c =
1 1 1 1 1 1 1 0
octave:4> byte2hex(c)
ans = FE
In MATLAB/Octave, conv and deconv are respectively correspond to multiplication and (division/modulo) operations for polynomials.
function out = multiply(A, x)
mult = mod(conv(A,x), 2); % poynomial multiplication
[~, modulo] = deconv(mult, [1 0 0 0 1 1 0 1 1]); %modulo operation
out = mod(modulo(end-7:end) , 2); %extract last 8 bits
end
For example to multiply 0x57 and 0x13
a = [1 0 1 0 1 1 1]; %0x57
b = [1 0 0 1 1]; %0x13
result = multiply(a,b)
result =
1 1 1 1 1 1 1 0
that is binary representation of 0xFE
Thank you for your interest. I am trying to implement AES in matlab. And I found the solution in the pages of http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf . Here is the function for the y= ( {09} . a ) multiply operation ;
function y = multiply_x9( a )
% Multiply byte A by 9 over finite field of AES
y2 = multiply_x2( a ) ;
y4 = multiply_x2( y2 ) ;
y8 = multiply_x2( y4 ) ;
y = mod( y8 + a , 2 ) ;
end
And also for the any matrix multiplication multiply_xx (a, b, p ) function can be used. Here is the function;
function y = multiply_xx (a, b, p )
% Determine input lengths and check if they are equal
n = length( a ) ;
if ( n ~= length(b) ) ,
error( 'Operand input lengths not equal to each other!' ) ;
elseif ( n ~= length(p) ) ,
error( 'Operand input lengths not equal to modulus length!' ) ;
end
% Initialize result to zeros and start iteration row by row
y = zeros( 1 , n ) ;
for i = 1 : n ,
m = a(i) * b ;
y = mod( y(1) * p + [ y(2:n) 0 ] + m , 2 ) ;
end
end

How to solve a linear system of matrices in scala breeze?

How to solve a linear system of matrices in scala breeze? ie, I have Ax = b, where A is a matrix (usually positive definite), and x and b are vectors.
I can see that there is a cholesky decomposition available, but I couldn't seem to find a solver? (if it was matlab I could do x = b \ A. If it was scipy I could do x = A.solve(b) )
Apparently, it is quite simple in fact, and built into scala-breeze as an operator:
x = A \ b
It doesnt use Cholesky, it uses LU decomposition, which is I think about half as fast, but they are both O(n^3), so comparable.
Well, I wrote my own solver in the end. I'm not sure if this is the optimal way to do it, but it doesn't seem unreasonable? :
// Copyright Hugh Perkins 2012
// You can use this under the terms of the Apache Public License 2.0
// http://www.apache.org/licenses/LICENSE-2.0
package root
import breeze.linalg._
object Solver {
// solve Ax = b, for x, where A = choleskyMatrix * choleskyMatrix.t
// choleskyMatrix should be lower triangular
def solve( choleskyMatrix: DenseMatrix[Double], b: DenseVector[Double] ) : DenseVector[Double] = {
val C = choleskyMatrix
val size = C.rows
if( C.rows != C.cols ) {
// throw exception or something
}
if( b.length != size ) {
// throw exception or something
}
// first we solve C * y = b
// (then we will solve C.t * x = y)
val y = DenseVector.zeros[Double](size)
// now we just work our way down from the top of the lower triangular matrix
for( i <- 0 until size ) {
var sum = 0.
for( j <- 0 until i ) {
sum += C(i,j) * y(j)
}
y(i) = ( b(i) - sum ) / C(i,i)
}
// now calculate x
val x = DenseVector.zeros[Double](size)
val Ct = C.t
// work up from bottom this time
for( i <- size -1 to 0 by -1 ) {
var sum = 0.
for( j <- i + 1 until size ) {
sum += Ct(i,j) * x(j)
}
x(i) = ( y(i) - sum ) / Ct(i,i)
}
x
}
}

imregionalmax matlab function's equivalent in opencv

I have an image of connected components(circles filled).If i want to segment them i can use watershed algorithm.I prefer writing my own function for watershed instead of using the inbuilt function in OPENCV.I have successfu How do i find the regionalmax of objects using opencv?
I wrote a function myself. My results were quite similar to MATLAB, although not exact. This function is implemented for CV_32F but it can easily be modified for other types.
I mark all the points that are not part of a minimum region by checking all the neighbors. The remaining regions are either minima, maxima or areas of inflection.
I use connected components to label each region.
I check each region for any point belonging to a maxima, if yes then I push that label into a vector.
Finally I sort the bad labels, erase all duplicates and then mark all the points in the output as not minima.
All that remains are the regions of minima.
Here is the code:
// output is a binary image
// 1: not a min region
// 0: part of a min region
// 2: not sure if min or not
// 3: uninitialized
void imregionalmin(cv::Mat& img, cv::Mat& out_img)
{
// pad the border of img with 1 and copy to img_pad
cv::Mat img_pad;
cv::copyMakeBorder(img, img_pad, 1, 1, 1, 1, IPL_BORDER_CONSTANT, 1);
// initialize binary output to 2, unknown if min
out_img = cv::Mat::ones(img.rows, img.cols, CV_8U)+2;
// initialize pointers to matrices
float* in = (float *)(img_pad.data);
uchar* out = (uchar *)(out_img.data);
// size of matrix
int in_size = img_pad.cols*img_pad.rows;
int out_size = img.cols*img.rows;
int x, y;
for (int i = 0; i < out_size; i++) {
// find x, y indexes
y = i % img.cols;
x = i / img.cols;
neighborCheck(in, out, i, x, y, img_pad.cols); // all regions are either min or max
}
cv::Mat label;
cv::connectedComponents(out_img, label);
int* lab = (int *)(label.data);
in = (float *)(img.data);
in_size = img.cols*img.rows;
std::vector<int> bad_labels;
for (int i = 0; i < out_size; i++) {
// find x, y indexes
y = i % img.cols;
x = i / img.cols;
if (lab[i] != 0) {
if (neighborCleanup(in, out, i, x, y, img.rows, img.cols) == 1) {
bad_labels.push_back(lab[i]);
}
}
}
std::sort(bad_labels.begin(), bad_labels.end());
bad_labels.erase(std::unique(bad_labels.begin(), bad_labels.end()), bad_labels.end());
for (int i = 0; i < out_size; ++i) {
if (lab[i] != 0) {
if (std::find(bad_labels.begin(), bad_labels.end(), lab[i]) != bad_labels.end()) {
out[i] = 0;
}
}
}
}
int inline neighborCleanup(float* in, uchar* out, int i, int x, int y, int x_lim, int y_lim)
{
int index;
for (int xx = x - 1; xx < x + 2; ++xx) {
for (int yy = y - 1; yy < y + 2; ++yy) {
if (((xx == x) && (yy==y)) || xx < 0 || yy < 0 || xx >= x_lim || yy >= y_lim)
continue;
index = xx*y_lim + yy;
if ((in[i] == in[index]) && (out[index] == 0))
return 1;
}
}
return 0;
}
void inline neighborCheck(float* in, uchar* out, int i, int x, int y, int x_lim)
{
int indexes[8], cur_index;
indexes[0] = x*x_lim + y;
indexes[1] = x*x_lim + y+1;
indexes[2] = x*x_lim + y+2;
indexes[3] = (x+1)*x_lim + y+2;
indexes[4] = (x + 2)*x_lim + y+2;
indexes[5] = (x + 2)*x_lim + y + 1;
indexes[6] = (x + 2)*x_lim + y;
indexes[7] = (x + 1)*x_lim + y;
cur_index = (x + 1)*x_lim + y+1;
for (int t = 0; t < 8; t++) {
if (in[indexes[t]] < in[cur_index]) {
out[i] = 0;
break;
}
}
if (out[i] == 3)
out[i] = 1;
}
The following listing is a function similar to Matlab's "imregionalmax". It looks for at most nLocMax local maxima above threshold, where the found local maxima are at least minDistBtwLocMax pixels apart. It returns the actual number of local maxima found. Notice that it uses OpenCV's minMaxLoc to find global maxima. It is "opencv-self-contained" except for the (easy to implement) function vdist, which computes the (euclidian) distance between points (r,c) and (row,col).
input is one-channel CV_32F matrix, and locations is nLocMax (rows) by 2 (columns) CV_32S matrix.
int imregionalmax(Mat input, int nLocMax, float threshold, float minDistBtwLocMax, Mat locations)
{
Mat scratch = input.clone();
int nFoundLocMax = 0;
for (int i = 0; i < nLocMax; i++) {
Point location;
double maxVal;
minMaxLoc(scratch, NULL, &maxVal, NULL, &location);
if (maxVal > threshold) {
nFoundLocMax += 1;
int row = location.y;
int col = location.x;
locations.at<int>(i,0) = row;
locations.at<int>(i,1) = col;
int r0 = (row-minDistBtwLocMax > -1 ? row-minDistBtwLocMax : 0);
int r1 = (row+minDistBtwLocMax < scratch.rows ? row+minDistBtwLocMax : scratch.rows-1);
int c0 = (col-minDistBtwLocMax > -1 ? col-minDistBtwLocMax : 0);
int c1 = (col+minDistBtwLocMax < scratch.cols ? col+minDistBtwLocMax : scratch.cols-1);
for (int r = r0; r <= r1; r++) {
for (int c = c0; c <= c1; c++) {
if (vdist(Point2DMake(r, c),Point2DMake(row, col)) <= minDistBtwLocMax) {
scratch.at<float>(r,c) = 0.0;
}
}
}
} else {
break;
}
}
return nFoundLocMax;
}
I do not know if it is what you want, but in my answer to this post, I gave some code to find local maxima (peaks) in a grayscale image (resulting from distance transform).
The approach relies on subtracting the original image from the dilated image and finding the zero pixels).
I hope it helps,
Good luck
I had the same problem some time ago, and the solution was to reimplement the imregionalmax algorithm in OpenCV/Cpp. It is not that complicated, because you can find the C++ source code of the function in the Matlab distribution. (somewhere in toolbox). All you have to do is to read carefully and understand the algorithm described there. Then rewrite it or remove the matlab-specific checks and you'll have it.

Matlab, if condition without loop

There are matices A(n,1), B(n,1) and the following condition inside a loop
for i=1:m
if ( A(i, 1) > error )
B(i,1) = 0;
else
B(i,1) = exp (-A(i,1) / 100)
end
end
How to rewrite this condition without using any loop? Is it possible something like that
if ( A(:, 1) > error )
B(:,1) = 0;
else
B(:,1) = exp (-A(:,1) / 100)
end
Use logical indexing:
idxs = (A > error);
B( idxs) = 0;
B(~idxs) = exp(-A(~idxs) / 100);
You were close with your suggestion. The key is to form a "logical index."
i = A(:,1) > error;
B(i,:) = 0;
B(~i,:) = exp (-A(:,1) / 100);
Since your matrices A and B are vectors (one-dimensional matrices), the (:,1) and (i,:) aren't necessary in this case but as they were in your initial formulation, I left them in. If you were using multi-dimensional matrices instead (m * n) you could form an (m * n) logical index rather than (m * 1) by doing i = A > error; instead of i = A(:,1) > error;