Manually upsample/replicate matrix - matlab

I'm trying to upsample a matrix by two by replicating another matrix, but i'm confused with the code, basically what i want is if:
Y = [1,2]
then the upsampled version would look like:
Up = [1,1,2,2;1,1,2,2]
What i've written so far is:
[row,col] = size(y)
Up = zeros(row*2,col*2);
for i = 1:2:row*2
for j = 1:2:col*2
Up(i, j) = Y(i,j);
Up(i+1, j) = Y(i,j);
Up(i, j+1) = Y(i,j);
Up(i+1, j+1) = Y(i,j);
end
end
but it says Index exceeds matrix dimensions, which i understand is because of the +1s but i'm not sure how else to go about doing this...

Data:
Y = [1,2]; % matrix
n = 2; % repetition factor
Solution using the repelem function (introduced in R2015a):
Up = repelem(Y,n,n);
Solution using indexing;
Up = Y(ceil(1/n:1/n:end), ceil(1/n:1/n:end));
Solution using a Kronecker product:
Up = kron(Y, ones(n))

The solution i ended up using is:
[row,col] = size(Y);
Up = zeros(row*2,col*2);
idx_row = 1;
for i = 1:D:row
idx_col = 1;
for j = 1:D:col
Up(i:i+1, j:j+1) = repmat(repmat(Y(idx_row,idx_col),1,2),2,1);
idx_col = idx_col + 1;
end
idx_row = idx_row + 1;
end

Related

How to correct grid search?

Trying to find the optimal hyperparameters for my svm model using a grid search, but it simply returns 1 for the hyperparameters.
function evaluations = inner_kfold_trainer(C,q,k,features_xy,labels)
features_xy_flds = kdivide(features_xy, k);
labels_flds = kdivide(labels, k);
evaluations = zeros(k,3);
for i = 1:k
fprintf('Fold %i of %i\n',i,k);
train_data = cell2mat(features_xy_flds(1:end ~= i));
train_labels = cell2mat(labels_flds(1:end ~= i));
test_data = cell2mat(features_xy_flds(i));
test_labels = cell2mat(labels_flds(i));
%AU1
train_labels = train_labels(:,1);
test_labels = test_labels(:,1);
[k,~] = size(test_labels);
%train
sv = fitcsvm(train_data,train_labels, 'KernelFunction','polynomial', 'PolynomialOrder',q,'BoxConstraint',C);
sv.predict(test_data);
%Calculate evaluative measures
%svm_outputs = zeros(k,1);
sv_predictions = sv.predict(test_data);
[precision,recall,F1] = evaluation(sv_predictions,test_labels);
evaluations(i,1) = precision;
evaluations(i,2) = recall;
evaluations(i,3) = F1;
end
save('eval.mat', 'evaluations');
end
an inner-fold cross validation function
and below the grid function where something seems to be going wrong
function [q,C] = grid_search(features_xy,labels,k)
% n x n grid
n = 3;
q_grid = linspace(1,19,n);
C_grid = linspace(1,59,n);
tic
evals = zeros(n,n,3);
for i = 1:n
for j = 1:n
fprintf('## i=%i, j=%i ##\n', i, j);
svm_results = inner_kfold_trainer(C_grid(i), q_grid(j),k,features_xy,labels);
evals(i,j,:) = mean(svm_results(:,:));
% precision only
%evals(i,j,:) = max(svm_results(:,1));
toc
end
end
f = evals;
% retrieving the best value of the hyper parameters, to use in the outer
% fold
[M1,I1] = max(f);
[~,I2] = max(M1(1,1,:));
index = I1(:,:,I2);
C = C_grid(index(1))
q = q_grid(index(2))
end
When I run grid_search(features_xy,labels,8) for example, I get C=1 and q=1, for any k(the no. of folds) value. Also features_xy is a 500*98 matrix.

Matlab Code for Linear System by Central Difference Method

I have a linear system Ay = b, which is created by matrix looks like this:
Here attempt to find the curves based on the matrix in the image description:
n = 10;
x0 = 0;
xn = 1;
h = 1/n;
y0 = 0;
y1 = 0;
x = zeros(1:n-1);
for i = 1:n-1;
x(i) = i*h
end
A =zeros(n-1);
for j = 1:n-2;
A(j,j+1) = (1+h/2);
A(j,j) = (h*exp(x(j))-2);
A(j+1,j) = (1-h/2);
end
A(n-1,n-1) = (h*exp(x(n-1))-2);
b = zeros(1,n-1); %Right-hand side vector
for i = 1:n-1
b(i)=h^2*((exp(x(i))-pi^2)*sin(pi*x(i))+pi*cos(pi*x(i)));
end
b=b';
y = zeros(1,n-1);
y = inv(A)*b % Solving for y
figure
plot(x,y,x,sin(x))
This is code that I create but the curves disappear, anyone can help me to check my code?

Subscripted assignment dimension mismatch in matlab

I executed this code using Feature Matrix 517*11 and Label Matrix 517*1. But once the dimensions of matrices change the code cant be run. How can I fix this?
The error is:
Subscripted assignment dimension mismatch.
in this line :
edges(k,j) = quantlevels(a);
Here is my code:
function [features,weights] = MI(features,labels,Q)
if nargin <3
Q = 12;
end
edges = zeros(size(features,2),Q+1);
for k = 1:size(features,2)
minval = min(features(:,k));
maxval = max(features(:,k));
if minval==maxval
continue;
end
quantlevels = minval:(maxval-minval)/500:maxval;
N = histc(features(:,k),quantlevels);
totsamples = size(features,1);
N_cum = cumsum(N);
edges(k,1) = -Inf;
stepsize = totsamples/Q;
for j = 1:Q-1
a = find(N_cum > j.*stepsize,1);
edges(k,j) = quantlevels(a);
end
edges(k,j+2) = Inf;
end
S = zeros(size(features));
for k = 1:size(S,2)
S(:,k) = quantize(features(:,k),edges(k,:))+1;
end
I = zeros(size(features,2),1);
for k = 1:size(features,2)
I(k) = computeMI(S(:,k),labels,0);
end
[weights,features] = sort(I,'descend');
%% EOF
function [I,M,SP] = computeMI(seq1,seq2,lag)
if nargin <3
lag = 0;
end
if(length(seq1) ~= length(seq2))
error('Input sequences are of different length');
end
lambda1 = max(seq1);
symbol_count1 = zeros(lambda1,1);
for k = 1:lambda1
symbol_count1(k) = sum(seq1 == k);
end
symbol_prob1 = symbol_count1./sum(symbol_count1)+0.000001;
lambda2 = max(seq2);
symbol_count2 = zeros(lambda2,1);
for k = 1:lambda2
symbol_count2(k) = sum(seq2 == k);
end
symbol_prob2 = symbol_count2./sum(symbol_count2)+0.000001;
M = zeros(lambda1,lambda2);
if(lag > 0)
for k = 1:length(seq1)-lag
loc1 = seq1(k);
loc2 = seq2(k+lag);
M(loc1,loc2) = M(loc1,loc2)+1;
end
else
for k = abs(lag)+1:length(seq1)
loc1 = seq1(k);
loc2 = seq2(k+lag);
M(loc1,loc2) = M(loc1,loc2)+1;
end
end
SP = symbol_prob1*symbol_prob2';
M = M./sum(M(:))+0.000001;
I = sum(sum(M.*log2(M./SP)));
function y = quantize(x, q)
x = x(:);
nx = length(x);
nq = length(q);
y = sum(repmat(x,1,nq)>repmat(q,nx,1),2);
I've run the function several times without getting any error.
I've used as input for "seq1" and "seq2" arrays such as 1:10 and 11:20
Possible error might rise in the loops
for k = 1:lambda1
symbol_count1(k) = sum(seq1 == k);
end
if "seq1" and "seq2" are defined as matrices since sum will return an array while
symbol_count1(k)
is expected to be single value.
Another possible error might rise if seq1 and seq2 are not of type integer since they are used as indexes in
M(loc1,loc2) = M(loc1,loc2)+1;
Hope this helps.

For loop output as an array

I wrote a code in Matlab which I predefine the variable "a" and then set up a for loop of 5 iterations where the variable "a" goes through some basic operations. However, the for loop output only saves the fifth iteration of "a." How do I save all 5 iterations in a 1x5 array?
The code is as follows:
a = 10;
k = 0.5;
n = 2;
for m = 1:5
a = a + (a*k) + n;
end
Edit:
I just found it that I have to create a new variable.
a = 10;
k = 0.5;
n = 2;
a_n = zeros(1,5);
for m = 1:5
a = a + (a*k) + n;
a_n(m) = a;
end
You may need to store value of a after each iteration into an another variable x
a = 10;
k = 0.5;
n = 2;
for m = 1:5
a = a + (a*k) + n;
x(m) = a;
end
x
Output:
x =
17.000 27.500 43.250 66.875 102.312
You would need to use a different variable to store the 5 iterations as an array.
Code would look something like this:
a = 10;
k = 0.5;
n = 2;
b = [];
for m = 1:5
a = (a + (a*k) + n)
b = [b a];
end
You can now print b for all 5 iteration values.
Here is an alternate way to update values into the 1-D matrix.

Prewitt Filter implementation Matlab

I'm trying to implement the Prewitt Filter in Matlab. I know that Matlab has already this kind of filter but I need to code it myself. Below is my code, the only problem is that at the end of the filtering I get a bright image instead of seeing the edges.
I'm implementing the filter using the separability property of the Prewitt Filter. Any ideas? I will appreciate very much your help.
%% 3x3 Prewitt Filter
close all
imageIn = imread('images/Bikesgray.jpg');
imageGx = zeros(size(imageIn));
imageGy = zeros(size(imageIn));
imageOut = zeros(size(imageIn));
ny = size(imageIn, 1);
nx = size(imageIn, 2);
average = 3;
imshow(imageIn);
u = [];
v = [];
tic
%Compute Gx
%For every row use the mask (-1 0 1)
for i = 1:ny
u = imageIn(i,:);
v = zeros(1, nx);
for k = 2:nx-1
v(k) = (uint32(-1*u(k-1))+uint32(0*u(k))+uint32(u(k+1)));
end
v(1) = (uint32(-1*u(2))+uint32(0*u(1))+uint32(u(2)));
v(nx) = (uint32(-1*u(nx-1))+uint32(0*u(nx))+uint32(u(nx-1)));
imageGx(i,:) = v;
end
%For every column use the mask (1 1 1)
for j = 1:nx
u = imageGx(:,j);
v = zeros(ny, 1);
for k = 2:ny-1
v(k) = (uint32(u(k-1))+uint32(u(k))+uint32(u(k+1)));
end
v(1) = (uint32(u(2))+uint32(u(1))+uint32(u(2)));
v(ny) = (uint32(u(ny-1))+uint32(u(ny))+uint32(u(ny-1)));
imageGx(:,j) = v;
end
%Compute Gy
%For every row use the mask (1 1 1)
for i = 1:ny
u = imageIn(i,:);
v = zeros(1, nx);
for k = 2:nx-1
v(k) = (uint32(u(k-1))+uint32(u(k))+uint32(u(k+1)));
end
v(1) = (uint32(u(2))+uint32(u(1))+uint32(u(2)));
v(nx) = (uint32(u(nx-1))+uint32(u(nx))+uint32(u(nx-1)));
imageGy(i,:) = v;
end
%For every column use the mask (1 0 -1)
for j = 1:nx
u = imageGy(:,j);
v = zeros(ny, 1);
for k = 2:ny-1
v(k) = (uint32(u(k-1))+uint32(0*u(k))+uint32(-1*u(k+1)));
end
v(1) = (uint32(u(2))+uint32(0*u(1))+uint32(-1*u(2)));
v(ny) = (uint32(u(ny-1))+uint32(0*u(ny))+uint32(-1*u(ny-1)));
imageGy(:,j) = v;
end
toc
figure
imshow(imageGx, [0 255]);
figure
imshow(imageGy, [0 255]);
%Compute the magnitude G = sqrt(Gx^2 + Gy^2);
imageOut(:,:) = sqrt(imageGx(:,:).^2 + imageGy(:,:).^2);
figure
imshow(imageOut, [0 255]);
It's too bad you didn't use convn (convolution), since the weighted sum just screams it.
In a nutshell you produce Gx,Gy by using convn on the image matrix, using the appropriate kernels, as described in wikipedia
The solution was really obvious but took me some time to figure it out.
All I did is change the uint32 to int32 and be sure to perform the operations (e.g. multiplying by -1) after changing the values from uint32 to int32.