I've a vector and a matrix:
1
1
0 0
0 0
I want to prepend the vector to matrix to produce :
1 0 0
1 0 0
I have so far :
val dv = DenseVector(1.0,1.0);
val dm = DenseMatrix.zeros[Double](2,2)
Reading the API : http://www.scalanlp.org/api/breeze/#breeze.linalg.DenseMatrix
and both these docs :
https://github.com/scalanlp/breeze/wiki/Quickstart https://github.com/scalanlp/breeze/wiki/Linear-Algebra-Cheat-Sheet
But this operation does not appear to be available ?
Is there a method/function to prepend a vector of ones to a Matrix ?
Another option here. Firstly convert the DenseVector to a 2X1 matrix and then use the DenseMatrix.horzcat() method:
val newMat = DenseMatrix.horzcat(new DenseMatrix(2,1,dv.toArray), dm)
# breeze.linalg.DenseMatrix[Double] = 1.0 0.0 0.0
# 1.0 0.0 0.0
newMat.rows
# 2
newMat.cols
# 3
You can make a function to create your dense matrix with a column of ones prepended:
def prependOnesColumn[V](original: DenseMatrix[V]): DenseMatrix[V] = {
val ones = DenseMatrix.ones(original.rows, 1)
val dataWithOnes = ones.data ++ original.data
DenseMatrix.create(original.rows, original.cols + 1, dataWithOnes)
}
Related
I'm unsure how to phrase the question, but I think an example will help. Suppose I have a vector y = [3;1;4;1;6]. I want to create the matrix Y =
[0 0 1 0 0 0;
1 0 0 0 0 0;
0 0 0 1 0 0;
1 0 0 0 0 0;
0 0 0 0 0 1]
↑ ↑ ↑ ↑ ↑ ↑
1 2 3 4 5 6
where the element on each column is one or zero corresponding to the value in the vector.
I found that I could do it using
Y = []; for k = 1:max(y); Y = [Y (y==k)]; end
Can I do it without a for loop (and is this method more efficient if y has thousands of elements)?
Thanks!
Your method is not efficient because you're growing the size of Y in the loop which is not a good programming practice. Here is how your code can be fixed:
Ele = numel(y);
Y= zeros(Ele, max(y));
for k = 1:Ele
Y (k,y(k))= 1;
end
And here is an alternative approach without a loop:
Ele = numel(y); %Finding no. of elements in y
Y= zeros(Ele, max(y)); % Initiailizing the matrix of the required size with all zeros
lin_idx = sub2ind(size(Y), 1:Ele, y.'); % Finding linear indexes
Y(lin_idx)=1 % Storing 1 in those indexes
You can use bsxfun:
result = double(bsxfun(#eq, y(:), 1:max(y)));
If you are running the code on Matlab version R2016b or later, you can simplify the syntax to
result = double(y(:)==(1:max(y)));
Another approach, possibly more efficient, is to fill in the values directly using accumarray:
result = accumarray([(1:numel(y)).' y(:)], 1);
I found another solution:
E = eye(max(y));
Y = E(y,:);
Another solution:
Y = repmat(1:max(y), size(y)) == repmat(y, 1, max(y))
I have a binary vector, if I find a 0 in the vector I want to make the adjacent elements 0 if they are not already.
For example if input = [1 1 0 1 1] I want to get output = [1 0 0 0 1]
I tried the following but it's messy and surely there is a neater way:
output=input;
for i = 1:length(input)
if(input(i) == 0)
output(i-1)=0;
output(i+1)=0;
end
end
In = [1, 1, 0, 1, 1]; % note that input is a MATLAB function already and thus a bad choice for a variable name
Find the zeros:
ind_zeros = ~In; % or In == 0 if you want to be more explicit
now find the indicies before and after
ind_zeros_dilated = ind_zeros | [ind_zeros(2:end), false] | [false, ind_zeros(1:end-1)]
Finally set the neighbours to zero:
Out = In;
Out(ind_zeros_dilated) = 0
For fun, an alternative way to calculate ind_zeros_dilated is to use convolution:
ind_zeros_dilated = conv(ind_zeros*1, [1,1,1],'same') > 0 %// the `*1` is just a lazy way to cast the logical vector ind_zeros to be of type float
I want to compare two image chunks such that if they are exactly the same, the result must be 1, and if they match 60 percent, the answer must be 0.6.
In Matlab, I can do this using corr2 command, but in python I couldn't find a way. I have tried numpy.corrcoef but it returns a matrix and scipy.signal.correlate2d returns the same.
This is what I have tried:
import numpy as np
import matplotlib.pyplot as plt
from skimage.filter import threshold_otsu
import matplotlib.cm as cm
import Image
import scipy
from PIL import Image as im
fname = 'testi.jpg'
image = Image.open(fname).convert("L")
arr = np.asarray(image)
global_thresh = threshold_otsu(arr)
global_otsu = arr >= global_thresh
global_otsu = np.invert(global_otsu).astype(int)
a1 = global_otsu[80:150,1350:1350+160]
fname1 = 'testi2.jpg'
image1 = Image.open(fname1).convert("L")
arr1 = np.asarray(image1)
global_thresh1 = threshold_otsu(arr1)
global_otsu1 = arr1 >= global_thresh1
global_otsu1 = np.invert(global_otsu1).astype(int)
a2 = global_otsu1[80:150,1350:1350+160]
co = scipy.signal.correlate2d(a1,a2)
plt.gray()
plt.subplot(121)
plt.imshow(a1)
plt.subplot(122)
plt.imshow(a2)
plt.show()
and the result is:
[[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
...,
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]]
These are the images that I want to compare:
Since you want to compare pixel by pixel you can perform correlation on the flattened images, :
cm = np.corrcoef(a1.flat, a2.flat)
cmcontains the symmetric correlation matrix where the off-diagonal element is the correlation coefficient. You get it by
r = cm[0, 1]
Edit:
There is a problem with using correlation for comparing images. If any of them is completely flat (all pixel the same value) the correlation is undefined.
If the images are binary you could instead simply calculate the percantage of equal pixels:
agreement = np.sum(a == b) / a.size
Suppose I have the following column vectors as
res1 = -0.81 res2 = 0.61
0.1 -0.4
-0.91 0.62
0.2 -0.56
0.63 -0.72
and I have two fixed constant D = 0.5. Now suppose an element of res1 is called X and an element of res2 is called Y. I have the following conditions
if (X > D && Y < -D)
output = 1
elseif (X < -D && Y > D)
output = -1
else
output = 0
end
My question is this:
Is it possible to "vectorize" these conditions to iterate over the entire vectors res1 and res2, such that my output vector would give (for example) :
output = -1
0
-1
0
1
?
I know I can do it via a loop, but I would prefer to avoid it since these vectors are actually quite large (>10000). I have attempted to use logical indexing, but to no avail (unless I'm implementing it wrong).
Any help would be appreciated!
You can use logical arrays to replace the conditional statements and scale them with appropriate scaling factors for the final output -
%// Logical arrays corresponding to the IF and ELSEIF conditional statements
case1 = res1>D & res2<-D
case2 = res1<-D & res2>D
%// Get the final output after multiplying each case with the
%// scaling factors 1 and -1 respectively.
%// The default value of `zero` for the ELSE part is automatically taken
%// care of because we are using logical array of ones and zeros anyway
output = case1 + -1*case2 %// or simply case1 - case2
Sample run -
>> res1
res1 =
-0.8100
0.1000
-0.9100
0.2000
0.6300
>> res2
res2 =
0.6100
-0.4000
0.6200
-0.5600
-0.7200
>> output
output =
-1
0
-1
0
1
I need to write a script to automatically setup a matrix A. The size of this matrix is linked to the value of another variable in the workspace, N. In general, A will have N + N*(N-1)/2 rows and N columns.
The first N rows and N columns are basically just a diagonal matrix, which is easy to setup using diag.
I'm having problems setting up the lower part of the matrix. Basically, it needs to have the following form:
-1 0 0 0
0 -1 0 0
0 0 -1 0
0 0 0 -1
1 -1 0 0
1 0 -1 0
1 0 0 -1
0 1 -1 0
0 1 0 -1
0 0 1 -1
I'm sure the pattern is clear.
How do I code this so that Matlab sets up this matrix for ANY value of N?
Thanks
With some algebraic manipulation:
L=(N*(N+1)/2):-1:1;
R=ceil((sqrt(8*L+1)-1)/2);
A=bsxfun(#eq, N-1:-1:0, R')-bsxfun(#eq, N:-1:1, (L-(R.*(R-1))/2).');
UPDATE
Performance version including preallocation.
N=4;
result = zeros(N*(N+1)/2,N+1);
t = N;
endpos = 0;
for t = N:-1:1
result(endpos+1:endpos+t,:) = [zeros(t, N-t) ones(t,1) -eye(t)];
endpos = endpos + t;
end
result = result(:,2:end);
Note that I have replaced the while loop as you seem to prefer a for.
I will leave the original here as well for comparison:
Here you go:
result = [];
N = 4;
t = MaxN;
while t > 0
block = [zeros(t, N-t) ones(t,1) -eye(t)];
result = [result; block];
t = t-1;
end
result = result(:,2:end);
Thank everyone! I will post my own solution here (doesn't pre-allocate though). Might adjust it to #Dennis's solution.
N = max(size(a));
P = N*(N-1)/2;
A = zeros(N+P,N);
A(1:N,1:N) = diag(-a);
B=[];
for i = N-1:-1:1
Block = [zeros(i,N-1-i) ones(i,1) -eye(i)];
B = [B; Block];
clear Block
end
A(N+1:end,:) = B;
clear N P B i