In my code error is Index Exceeds Matrix Dimension - matlab

my code gives an error and that is Index exceeds matrix dimensions.It runs perfectly for nsample=10 but when I use nsamples=other value it gives error.
The error starts from line 108 that means when dataright(1:20) =
output(1:20);but it runs when I used dataright(1:10) = output(1:10).
function icall(block)
setup(block);
function setup(block)
block.NumInputPorts = 0;
block.NumOutputPorts = 4;
block.OutputPort(1).SamplingMode = 'sample';
%% Setup functional port to default
block.SetPreCompPortInfoToDefaults;
%% Setup output port
block.SampleTimes = [0 1];
block.SimStateCompliance = 'DefaultSimState';
block.RegBlockMethod('Start', #Start);
block.RegBlockMethod('Outputs', #Outputs); % Required
block.RegBlockMethod('Update', #Update);
block.RegBlockMethod('Terminate', #Terminate); % Required
block.RegBlockMethod('SetInputPortSamplingMode', #SetInpPortFrameData);
block.RegBlockMethod('PostPropagationSetup', #DoPostPropSetup);
function DoPostPropSetup(block)
% Setup Dwork
block.NumDworks = 4;
block.Dwork(1).Name = 'Nothing';
block.Dwork(1).Dimensions = 1;
block.Dwork(1).DatatypeID = 0;
block.Dwork(1).Complexity = 'Real';
block.Dwork(1).UsedAsDiscState = false;
block.Dwork(2).Name = 'Nothing1';
block.Dwork(2).Dimensions = 1;
block.Dwork(2).DatatypeID = 0;
block.Dwork(2).Complexity = 'Real';
block.Dwork(2).UsedAsDiscState = false;
block.Dwork(3).Name = 'Nothing2';
block.Dwork(3).Dimensions = 1;
block.Dwork(3).DatatypeID = 0;
block.Dwork(3).Complexity = 'Real';
block.Dwork(3).UsedAsDiscState = false;
block.Dwork(4).Name = 'Nothing3';
block.Dwork(4).Dimensions = 1;
block.Dwork(4).DatatypeID = 0;
block.Dwork(4).Complexity = 'Real';
block.Dwork(4).UsedAsDiscState = false;
%endfunction
%endfunction
function Start(block)
fullpathToDll = 'Z:\Farha\2015_02_26_photometer_Datenlogger\PC-Software\CGMultChan.dll';
fullpathToHeader = 'Z:\Farha\2015_02_26_photometer_Datenlogger\PC-Software\CGMultChan.h';
fullpathToHeader;
fullpathToDll;
loadlibrary(fullpathToDll, fullpathToHeader);
libfunctions ('CGMultChan');
delete(instrfindall);
serialPort = 'COM1';
IP = calllib('CGMultChan', 'CGMultChan_Connect', '192.168.100.158'); %Connect to Data Loger
if (IP == 0)
end
out = instrfind('Port', 'COM1');
%Open Serial COM Port
s = serial(serialPort);
set(s, 'BaudRate', 57600, 'DataBits', 8, 'Parity', 'none', 'StopBits', 1, 'FlowControl', 'none', 'Terminator', 'CR');
set(s, 'Timeout', 20);
fopen(s);
TI_ms = calllib('CGMultChan', 'CGMultChan_SetIntTime', .02 * 100);
tic
block.Dwork(1).Data = 1;
block.Dwork(2).Data = 2;
block.Dwork(3).Data = 3;
block.Dwork(4).Data = 5;
function Outputs(block)
block.OutputPort(1).Data = block.Dwork(1).Data; %+ %block.InputPort(1).Data;
block.OutputPort(2).Data = block.Dwork(2).Data;
block.OutputPort(3).Data = block.Dwork(3).Data;
block.OutputPort(4).Data = block.Dwork(4).Data;
count = 0;
function Update(block)
nsamples = 20
count = 0
while (count < nsamples)
BufferSize = 16;
pBuffer = libpointer('singlePtr', zeros(BufferSize, 1));
data2 = calllib('CGMultChan', 'CGMultChan_MeasureAll', pBuffer); %Measurement
output = pBuffer.Value
count = count + 1;
time(count) = toc; %Extract Elapsed Time
dataright(count) = output(1)
dataup(count) = output(2)
databack(count) = output(3)
datafront(count) = output(5)
end
dataright(1:20) = output(1:20);
dataup(1:20) = output(1:20);
databack(1:20) = output(1:20);
datafront(1:20) = output(1:20);
block.Dwork(1).Data = double(dataright(1));
block.Dwork(2).Data = double(dataup(2));
block.Dwork(3).Data = double(databack(3));
block.Dwork(4).Data = double(datafront(5));
%end Update
function SetInpPortFrameData(block, idx, fd)
block.InputPort(idx).SamplingMode = fd;
for i = 1:block.NumOutputPorts
block.OutputPort(i).SamplingMode = fd;
end
%%
function Terminate(block)
serialPort = 'COM1';
s = serial(serialPort);
fclose(s);
clear pBuffer;
calllib('CGMultChan', 'CGMultChan_Disconnect'); %Disconnect from Data Logger

This is a Level 2 S function code which generates simulink block. It connects a data logger with computer. That means its an object oriented code. I solved the problem changing the buffer size pbuffer=500. So that matrix size of data output is increased.

Related

How to create object within function MatLab without creating a new file

I am working on a project with the following specs:
https://drive.google.com/file/d/14xaCK-1Mpd8FXM-19pfFC1UTk2V9oXkQ/view?usp=sharing
My code is attached below.
How do I get my final output as a data object and info object like they are asking, without creating a new class file? The format required is in the picture below.
Final format required:
function [data,info] = OneNormLPxxx(A,b)
%L1 norm minimization for a given A and b.
% Detailed explanation goes here
count = 0;
b_vect = b;
[m,n] = size(A);
max_count = 3*nchoosek(m,n);
set_B = 1:n;
M = inv(A(set_B, :));
is_opt = 0;
while (is_opt == 0)
if (det(A(set_B,:)) == 0)
info = untitled4;
info.run = "Failure";
info.msg = "Degeneracy Problem";
data = untitled3;
return
end
if (max_count <= count)
info = untitled4;
info.run = "Failure";
info.msg = "Arithmetic Problem";
data = untitled3;
return
end
set_B_Comp = setdiff(1:m,set_B);
x_temp = M*b_vect(set_B);
h = A*x_temp - b_vect;
h(set_B_Comp) = A(set_B_Comp,:)*x_temp - b_vect(set_B_Comp);
y_vect = zeros(m, 1);
y_vect(set_B_Comp) = sign(h(set_B_Comp));
y_vect(set_B) = -(M')*((A(set_B_Comp,:)')*y_vect(set_B_Comp));
abs_y_B = abs(y_vect(set_B));
if all(abs_y_B <= 1)
is_opt = 1;
x_opt = x_temp;
opt_val = sum(abs(A*x_opt - b_vect));
data = untitled3;
data.obj = opt_val;
data.x = x_opt;
data.loop = count;
info = untitled4;
info.run = "Success";
return
% return B and x
else
all_index_y_vect_more_than_1 = find(abs(y_vect(set_B)) > 1);
s = all_index_y_vect_more_than_1(1);
y_s = y_vect(s);
t_vect = zeros(m, 1);
t_vect(set_B_Comp) = -(sign(y_s))*(y_vect(set_B_Comp)).*(A(set_B_Comp,:)*M(:,s));
cur_min = abs(h(set_B_Comp(1)))/t_vect(set_B_Comp(1)) + 1;
cur_r = set_B_Comp(1);
for j = set_B_Comp
h_j = h(j);
t_j = t_vect(j);
temp1 = abs(h_j)/t_j;
if (temp1 < cur_min) && (temp1 > 0) && (t_j > 0)
cur_min = temp1;
cur_r = j;
end
end
r = cur_r;
j_s = set_B(s);
set_B_new = setdiff(union(set_B, r), j_s);
set_B = set_B_new;
set_B_Comp = setdiff(1:m,set_B);
theta = (A(r,:)*M)';
M(:,s) = (1/theta(s))*M(:,s);
for j = 1:n
if (j ~= s)
M(:,j) = M(:,j) - theta(j)*M(:,s);
end
end
end
count = count + 1;
end
end
Rather than using
info = untitled4;
Use
info = struct();
This will create a MATLAB structure for storing your data.

I need help plotting different permutations of an if/else command in different colors on the same plot

Basically I have a code where it produces a plot of all possible permutations between Cost and Reliability. There's a total of 864 data points split up between 8 rows. Five of the rows have 2 options and three of them 3 options.
Given here is a copy of my code. I'm trying to have the permutations of 'Other Cameras' and 'Depth & Structure Testing' have a different color with the other six possibilities. I tried using the 'gscatter' command but didn't have much luck with it.
I believe I need to have the scatter command in the if/else statements themselves, although I'm not too sure what to plot in the 'X' and 'Y' for the 'scatter' command. Currently my code is set up for plotting all the data in one color. I deleted my code with the 'gscatter' because I got many errors and when I tried to fix them the plot ultimately didn't work as planned.
% Pareto_Eval
baseline_cost = 45;
nrows = 8;
%Initialize Variables
for aa = 1:nrows
cost_delta(aa) = 0;
reliability(aa) = 1;
end
icount = 1;
%Propulsion
for row1 = 1:2
if row1 == 1
cost_delta(1)= -7;
reliability(1) = 0.995;
elseif row1==2
cost_delta(1)=0;
reliability(1)=.99;
end
%Entry Mode
for row2 = 1:2
if row2 == 1
cost_delta(2) = -3;
reliability(2) = .99;
else
cost_delta(2) = 0;
reliability(2) = .98;
end
%Landing Method
for row3 = 1:3
if row3 == 1 %if needs declaration
cost_delta(3)= 0;
reliability(3) = .99;
elseif row3 == 2 %elseif needs declaration
cost_delta(3) = 4;
reliability(3) = .995;
else %else does not need declaration
cost_delta(3) = -2;
reliability(3) = .95;
end
%Lander Type
for row4 = 1:3
if row4 == 1
cost_delta(4)= 10;
reliability(4) = .99;
elseif row4 == 2
cost_delta(4) = 0;
reliability(4) = .99;
else
cost_delta(4) = 15;
reliability(4) = .95;
end
%Rover Type
for row5 = 1:2
if row5 == 1
cost_delta(5)= -2;
reliability(5) = .98;
else
cost_delta(5) = 0;
reliability(5) = .975;
end
%Power Source
for row6 = 1:2
if row6 == 1
cost_delta(6) = -3;
reliability(6) = .95;
else
cost_delta(6) = 0;
reliability(6) = .995;
end
%Depth & Structure Testing
for row7 = 1:2
if row7 == 1
cost_delta(7) = 0;
reliability(7) = .99;
else
cost_delta(7) = 2;
reliability(7) = .85;
end
%Other Cameras
for row8 = 1:3
if row8 == 1
cost_delta(8)= -1;
reliability(8) = .99;
elseif row8 == 2
cost_delta(8) = -1;
reliability(8) = .99;
else
cost_delta(8) = 0;
reliability(8) = .9801;
end
cost_delta_total = 0;
reliability_product = 1;
for bb=1:nrows
cost_delta_total = cost_delta_total + cost_delta(bb);
reliability_product = reliability_product*reliability(bb);
end
total_cost(icount) = baseline_cost + cost_delta_total;
total_reliability(icount) = reliability_product;
icount = icount + 1;
end; end; end; %Rows 1,2,3
end; end; end; %Rows 4,5,6
end; end; %Rows 7,8
%Plot the Pareto Evaluation
fignum=1;
figure(fignum)
sz = 5;
scatter(total_reliability, total_cost, sz, 'blue')
xlabel('Reliability')
ylabel('Cost')
title('Pareto Plot')
Any help is appreciated. I don't have a lot of experience with Matlab and I've tried looking around for help but nothing really worked.
Here is a sample code to make questions easier I created:
% Pareto_Eval
baseline_cost = 55;
nrows = 3;
%Initialize Variables
for aa = 1:nrows
cost_delta(aa) = 0;
reliability(aa) = 1;
end
icount = 1;
%Group 1
for row1 = 1:2
if row1 == 1
cost_delta(1)= 5;
reliability(1) = 0.999;
elseif row1==2
cost_delta(1) = 0;
reliability(1) = .995;
end
%Group 2
for row2 = 1:2
if row2 == 1
cost_delta(2) = 0;
reliability(2) = .98;
else
cost_delta(2) = -2;
reliability(2) = .95;
end
%Group 3
for row3 = 1:2
if row3 == 1
cost_delta(3) = 3;
reliability(3) = .997;
else
cost_delta(3) = 0;
reliability(3) = .96;
end
%initializing each row
cost_delta_total = 0;
reliability_product = 1;
for bb = 1:nrows
cost_delta_total = cost_delta_total + cost_delta(bb);
reliability_product = reliability_product*reliability(bb);
end
total_cost(icount) = baseline_cost + cost_delta_total;
total_reliability(icount) = reliability_product;
icount = icount + 1;
end
end
end
fignum=1;
figure(fignum)
sz = 25;
scatter(total_reliability, total_cost, sz)
xlabel('Reliability')
ylabel('Cost')
title('Pareto Plot')
Basically I need to make a plot in each if-loop, but I'm not sure how to do it and have them all on the same plot
sounds like an interesting project! Not sure if I understood your intended plots correctly, but hopefully the code below gets you a bit closer to what you are looking for.
I've started off with a rather deep mess of nested for loops (as you did) but kept it more concise bybuilding a permutations matrix.
counter = 0;
for propulsion_options = 1:2
for entry_mode = 1:2
for landing_method = 1:3
for lander_type = 1:3
for rover_type = 1:2
for power_source = 1:2
for depth_testing = 1:2
for other_cameras = 1:3
counter = counter +1
permutations(counter,:) = [...
propulsion_options,...
entry_mode,...
landing_method,...
lander_type,...
rover_type,...
power_source,...
depth_testing,...
other_cameras];
end
end
end
end
end
end
end
end
This way I kept the actual scoring out of the loops, and perhaps easier to tweak the values. I initialised the cost and reliabiltiy arrays to be the same size as the permutations array:
cost_delta = zeros(size(permutations));
reliability = zeros(size(permutations));
Then for each metric, I searched the permutations array for all occurances of each possible value and assigned the appropriate score:
%propulsion
propertyNo = 1;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = -7;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 0;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.995;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.99;
%entry_mode (2)
propertyNo = 2;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = -3;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 0;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.98;
%landing_method (3)
propertyNo = 3;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = 0;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 4;
cost_delta(find(permutations(:,propertyNo)==3),propertyNo) = -2;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.995;
reliability(find(permutations(:,propertyNo)==3),propertyNo) = 0.95;
%lander_type (3)
propertyNo = 4;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = 10;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 0;
cost_delta(find(permutations(:,propertyNo)==3),propertyNo) = 15;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==3),propertyNo) = 0.95;
%rover_type (2)
propertyNo = 5;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = -2;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 0;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.98;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.975;
%power_source (2)
propertyNo = 6;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = -3;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 0;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.95;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.995;
%depth_testing (2)
propertyNo = 7;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = 0;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 2;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.85;
%other_cameras (3)
propertyNo = 8;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = -1;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = -1;
cost_delta(find(permutations(:,propertyNo)==3),propertyNo) = 0;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==3),propertyNo) = 0.9801;
Then each permutation can have a total cost / reliabiltiy score by summing and takign the product along the second dimension:
cost_delta_total = sum(cost_delta,2);
reliability_product = prod(reliability,2);
Finally, you can plot all points (as per your original):
%Plot the Pareto Evaluation
fignum=1;
figure(fignum)
sz = 5;
scatter(reliability_product, cost_delta_total, sz, 'b')
xlabel('Reliability')
ylabel('Cost')
title('Pareto Plot')
or you can create an index into the permutations by searching for specific property values and plot these different colours (actually this bit answers your most specific question of how to plot two things on the same axes - you just need the hold on; command):
propertyNo = 7;
indexDepth1 = find(permutations(:,propertyNo)==1);
indexDepth2 = find(permutations(:,propertyNo)==2);
fignum=2;
figure(fignum)
sz = 5;
scatter(reliability_product(indexDepth1), cost_delta_total(indexDepth1), sz, 'k');
hold on;
scatter(reliability_product(indexDepth2), cost_delta_total(indexDepth2), sz, 'b');
xlabel('Reliability')
ylabel('Cost')
title('Pareto Plot')
legend('Depth & Structure Test 1','Depth & Structure Test 2')
propertyNo = 8;
indexCam1 = find(permutations(:,propertyNo)==1);
indexCam2 = find(permutations(:,propertyNo)==2);
indexCam3 = find(permutations(:,propertyNo)==3);
fignum=3;
figure(fignum)
sz = 5;
scatter(reliability_product(indexCam1), cost_delta_total(indexCam1), sz, 'k');
hold on;
scatter(reliability_product(indexCam2), cost_delta_total(indexCam2), sz, 'b');
scatter(reliability_product(indexCam3), cost_delta_total(indexCam3), sz, 'g');
xlabel('Reliability')
ylabel('Cost')
title('Pareto Plot')
legend('Other Camera 1','Other Camera 2','Other Camera 3')
Good luck with the mission! When is launch day?

Extrapolating value from function to a for loop and passing it back to the function

function Test()
a = 2;
b = 1;
c = 0.5;
q = 0.001;
r = 10;
function F = Useful(x) %calculates existing values for x with size 11
eq1 = (1*(0.903*x(2))^(-1))-(0.903*x(1));
eq2 = (1*(0.665*x(3))*(0.903*x(2))^(-1))-0.903*x(4);
eq3 = (1*(0.399*x(5))*(0.903*x(2)))-0.665*x(6);
eq4 = (1*(0.399*x(5))*(0.903*x(2))^2)-0.903*x(7);
eq5 = (1*(0.399*x(5))*(0.903*x(2))^3)-1*x(8);
eq6 = (1*(0.665*x(3))*(0.399*x(5))*(0.903*x(2)))-1*x(9);
eq7 = (1*(0.665*x(3))*(0.399*x(5))*(0.903*x(2))^2)-0.903*x(10);
eq8 = (1*(0.665*x(3))*(0.399*x(5)))-0.903*x(11);
eq9 = x(3)+x(4)+x(9)+x(10)+x(11)-a;
eq10 = x(5)+x(6)+x(7)+x(8)+x(9)+x(10)+x(11)-b;
eq11 = x(2)+x(6)+2*x(7)+3*x(8)+x(9)+2*x(10)-x(1)-x(4)-c;
F = [eq1;eq2;eq3;eq4;eq5;eq6;eq7;eq8; eq9; eq10; eq11];
end
Value(1,1) = 0;
for d = 2:100
x = fsolve(#Useful,x0,options); %Produces the x(1) to x(11) values
Value(1,d) = (x(3)+x(5))*d+Value(1,d-1); %Gives a new value after each iteration
a = a-x(3);
b = b-x(5);
c = c-x(2);
end
function Zdot = rhs(t,z) %z = (e1,e2,e3,e4,e5)
Zdot=zeros(5,1);
Zdot(1) = -1*z(1);
Zdot(2) = 1*z(1);
Zdot(3) = 1*z(1) - 1*z(2)*z(3);
Zdot(4) = 1*1*z(1) - Value(1,100)*H(z(3))*z(4)*z(4);
Zdot(5) = Value(1,100)*H(z(3))*(z(4));
end
function hill = H(x)
hill = q/(q+x^r);
end
[T,Y] = ode15s(#rhs, [0, 120], [1, 0, 1, 0, 0]); %Solve second function with values giving z(1) to z(5)
plot(T,Y(:,5))
end
I'm wondering, is it possible to pass on each Value obtained (Value (1), Value (2)... so on), into "function Zdot" or is only the final value possible to pass on? Essentially is this possible to implement:
function Zdot = rhs(t,z) %z = (e1,e2,e3,e4,e5)
Zdot=zeros(5,1);
Zdot(1) = -1*z(1);
Zdot(2) = 1*z(1);
Zdot(3) = 1*z(1) - 1*z(2)*z(3);
Zdot(4) = 1*1*z(1) - Value(1,d)*H(z(3))*z(4)*z(4);
Zdot(5) = Value(1,d)*H(z(3))*(z(4));
end
Any insights would be much appreciated and I would be extremely grateful. Thank you in advance!

MATLAB 'parfor' Loops Very Slow When Compared With 'for' loop

I have a script that I'm running, and at one point I have a loop over n objects, where I want n to be fairly large.
I have access to a server, so I put in a parfor loop. However, this is incredibly slow compared with a standard for loops.
For example, running a certain configuration ( the one below ) with the parfor loop on 35 workers took 68 seconds, whereas the for loop took 2.3 seconds.
I know there's stuff to do with array-broadcasting that can cause issues, but I don't know a lot about this.
n = 20;
r = 1/30;
tic
X = rand([2,n-1]);
X = [X,[0.5;0.5]];
D = sq_distance(X,X);
A = sparse((D < r) - eye(n));
% Infected set I
I = n;
[S,C] = graphconncomp(A);
compnum = C(I);
I_new = find(C == compnum);
I = I_new;
figure%('visible','off')
gplot(A,X')
hold on
plot(X(1,I),X(2,I),'r.')
hold off
title('time = 0')
axis([0,1,0,1])
time = 0;
t_max = 10; t_int = 1/100;
TIME = 1; T_plot = t_int^(-1) /100;
loops = t_max / T_plot;
F(loops) = struct('cdata',[],'colormap',[]);
F(1) = getframe;
% Probability of healing in interval of length t_int
heal_rate = 1/3; % (higher number is faster heal)
p_heal = t_int * heal_rate;
numhealed = 0;
while time < t_max
time = time+t_int;
steps = poissrnd(t_int,[n,1]);
parfor k = 1:n
for s = 1:steps(k)
unit_vec = unif_unitvector;
X_new = X(:,k) + unit_vec*t_int;
if ( X_new < 1 == ones(2,1) ) ...
& ( X_new > 0 == ones(2,1) )
X(:,k) = X_new;
end
end
end
D = sq_distance(X,X);
A = sparse((D < r) - eye(n));
[S,C] = graphconncomp(A);
particles_healed = binornd(ones(length(I),1),p_heal);
still_infected = find(particles_healed == 0);
I = I(still_infected);
numhealed = numhealed + sum(particles_healed);
I_new = I;
% compnum = zeros(length(I),1);
for i = 1:length(I)
compnum = C(I(i));
I_new = union(I_new,find(C == compnum));
end
I = I_new;
if time >= T_plot*TIME
gplot(A,X')
hold on
plot(X(1,I),X(2,I),'r.')
hold off
title(sprintf('time = %1g',time))
axis([0,1,0,1])
% fprintf('number healed = %1g\n',numhealed)
numhealed = 0;
F(TIME) = getframe;
TIME = TIME + 1;
end
end
toc

Converting Matlab gaussian derivatives to Opencv

I trying to convert an old exercise i made in matlab to OpenCV. Code is posted below. I havent been able to find any functions in OpenCv that does what i want, might be because of other names then what i expect.
Here are the outputs when taken the max response in each location as label. Clearly somethings wronge.
Here is the matlab code:
function responses = getBifResponsesEx(im, myEps, sigma, kernelSize)
if ( nargin == 3 )
if ( sigma >= 1 )
kernelSize = 6*sigma + 1;
else
kernelSize = 7;
end
end
responses = zeros(size(im,1), size(im,2), 7);
%
% Gaussian derivatives
%
kernVal = ceil(kernelSize/2) - 1;
x = (-kernVal:kernVal);
g = 1/(2*pi*sigma^2)*exp(-(x.^2./(2*(sigma^2))));
g = g/sum(g);
dg = -2*x/(2*sigma^2).*g*sigma;
ddg = ((2*x/(2*sigma^2)).^2 - 1/(sigma^2)).*g*sigma;
%
% Gaussian convolution of the image
%
s00 = filter2(g, im);
s00 = filter2(g', s00);
s10 = filter2(g', im);
s10 = filter2(dg, s10);
s01 = filter2(g, im);
s01 = filter2(dg', s01);
s11 = filter2(dg, im);
s11 = filter2(dg', s11);
s20 = filter2(g', im);
s20 = filter2(g', s20);
s20 = filter2(ddg, s20);
s02 = filter2(g, im);
s02 = filter2(g, s02);
s02 = filter2(ddg', s02);
%
% Symmetry types - MISSING CODE!!!!
%
lam = sigma^2*(s20+s02);
gam = sigma^2*(sqrt((s20-s02).^2+4*s11.^2));
responses(:,:,1) = myEps*s00;
responses(:,:,2) = 2*sigma*sqrt(s10.^2+s01.^2);
responses(:,:,3) = +lam;
responses(:,:,4) = -lam;
responses(:,:,5) = 2^-.5*(gam+lam);
responses(:,:,6) = 2^-.5*(gam-lam);
responses(:,:,7) = gam;
end
And here is my converted page. From what i can see, it goes wronge with the s20,s02 responses. Anyone able to tell me what to do?
void extract_bif_features(const cv::Mat & src,
std::vector<cv::Mat> & dst, BIFParams params)
{
float sigma = params.sigma;
float n=0;
int kernelSize;
if(sigma>=1)
kernelSize = 6*sigma + 1;
else
kernelSize = 7;
cv::Mat gray,p00,p10,p01,p11,p20,p02;
cv::cvtColor(src,gray,CV_BGR2GRAY);
auto kernVal = (int)ceil(kernelSize/2.0) - 1;
cv::Mat_<float> g(1,kernelSize);float*gp = g.ptr<float>();
cv::Mat_<float> dg(1,kernelSize);float*dgp = dg.ptr<float>();
cv::Mat_<float> ddg(1,kernelSize); float*ddgp = ddg.ptr<float>();
cv::Mat_<float> X(1,kernelSize);float*xp = X.ptr<float>();
auto gsum=0.0f;
for(int x = -kernVal;x<=kernVal;++x)
{
xp[x+kernVal] = x;
gp[x+kernVal] = 1/(2*CV_PI*sigma*sigma)*exp(-(x*x/(2*(sigma*sigma))));
gsum += gp[x+kernVal];
}
g = g/gsum;
cv::multiply((-2*X / (2*sigma*sigma)),g*sigma,dg);
cv::pow((2*X/(2*sigma*sigma)),2,ddg);
ddg -=1/(sigma*sigma);
cv::multiply(ddg,g*sigma,ddg);
std::cout << ddg<< std::endl;
std::cout << dg<< std::endl;
cv::sepFilter2D(gray,p00,CV_32FC1,g,g,cv::Point(-1,-1),0.0,cv::BORDER_REPLICATE); cv::sepFilter2D(gray,p01,CV_32FC1,dg,g,cv::Point(-1,-1),0.0,cv::BORDER_REPLICATE); cv::sepFilter2D(gray,p10,CV_32FC1,g,dg,cv::Point(-1,-1),0.0,cv::BORDER_REPLICATE); cv::sepFilter2D(gray,p11,CV_32FC1,dg,dg,cv::Point(-1,-1),0.0,cv::BORDER_REPLICATE);
//NOT SURE HERE
cv::sepFilter2D(gray,p20,CV_32FC1,g,ddg,cv::Point(-1,-1),0.0,cv::BORDER_REPLICATE);
//cv::sepFilter2D(p20,p20,CV_32FC1,1,g,cv::Point(-1,-1),0.0,cv::BORDER_REPLICATE); cv::sepFilter2D(gray,p02,CV_32FC1,g,ddg,cv::Point(-1,-1),0.0,cv::BORDER_REPLICATE); //cv::sepFilter2D(p02,p02,CV_32FC1,g,1,cv::Point(-1,-1),0.0,cv::BORDER_REPLICATE);
cv::filter2D(gray,p20,CV_32FC1,g,cv::Point(-1,-1),0.0,cv::BORDER_REPLICATE);
cv::filter2D(p20,p20,CV_32FC1,g,cv::Point(-1,-1),0.0,cv::BORDER_REPLICATE);
cv::filter2D(p20,p20,CV_32FC1,ddg,cv::Point(-1,-1),0.0,cv::BORDER_REPLICATE);
cv::filter2D(gray,p02,CV_32FC1,g,cv::Point(-1,-1),0.0,cv::BORDER_REPLICATE);
cv::filter2D(p02,p02,CV_32FC1,g.t(),cv::Point(-1,-1),0.0,cv::BORDER_REPLICATE);
cv::filter2D(p02,p02,CV_32FC1,ddg.t(),cv::Point(-1,-1),0.0,cv::BORDER_REPLICATE);
dst.resize(6);
auto sigma_square = sigma*sigma;
cv::Mat Lam = sigma_square * (p20+p02);
cv::Mat Gam ;
cv::sqrt((((p20-p02)*(p20-p02))+4*p11*p11),Gam);
Gam *= sigma_square ;
cv::Mat test = p10*p10;
//slop
cv::sqrt(p10*p10 + p01*p01,dst[0]);
dst[0] = dst[0]*2*sigma;//slop
//blob
dst[1] = Lam;
dst[2] = -1*Lam;
//line
dst[3] = sqrt(2.0f)*(Gam+Lam);
dst[4] = sqrt(2.0f)*(Gam-Lam);
//saddle
dst[5] = Gam;
}
The answer is from what i get sofar.
cv::multiply((p20-p02),(p20-p02),Gam); is not the same as Gam = (p20-p02)*(p20-p02);
Full Code: Classify according to higest response, Griffin(2008).
RIDAR_API void extract_bif_features(const cv::Mat & src,
std::vector<cv::Mat> & dst, BIFParams params)
{
float sigma = params.sigma;
float eta = params.eta;
int kernelSize;
if(sigma>=1)
kernelSize = 4*sigma + 1;
else
kernelSize = 5;
auto kernVal = (int)ceil(kernelSize/2.0) - 1;
cv::Mat_<float> g(1,kernelSize);float*gp = g.ptr<float>();
cv::Mat_<float> X(1,kernelSize);float*xp = X.ptr<float>();
auto gsum=0.0f;
for(int x = -kernVal;x<=kernVal;++x)
{
xp[x+kernVal] = x;
gp[x+kernVal] = 1/(2*CV_PI*sigma*sigma)*exp(-(x*x/(2*(sigma*sigma))));
gsum += gp[x+kernVal];
} g = g/gsum;
cv::Mat dg = -2*X.mul(g*sigma) / (2*sigma*sigma);
cv::Mat ddg = ((2*X/(2*sigma*sigma)).mul((2*X/(2*sigma*sigma))) - 1/(sigma*sigma)).mul(g*sigma);
cv::Mat gray,p00,p10,p01,p11,p20,p02;
cv::cvtColor(src,gray,CV_BGR2GRAY);
cv::filter2D(gray,p00,CV_32FC1,g);
cv::filter2D(p00,p00,CV_32FC1,g.t());
cv::filter2D(gray,p10,CV_32FC1,g.t());
cv::filter2D(p10,p10,CV_32FC1,dg);
cv::filter2D(gray,p01,CV_32FC1,g);
cv::filter2D(p01,p01,CV_32FC1,dg.t());
cv::filter2D(gray,p11,CV_32FC1,dg);
cv::filter2D(p11,p11,CV_32FC1,dg.t());
cv::filter2D(gray,p20,CV_32FC1,g.t());
cv::filter2D(p20,p20,CV_32FC1,g.t());
cv::filter2D(p20,p20,CV_32FC1,ddg);
cv::filter2D(gray,p02,CV_32FC1,g);
cv::filter2D(p02,p02,CV_32FC1,g);
cv::filter2D(p02,p02,CV_32FC1,ddg.t());
#ifdef DISPLAY_WHILE_RUNNING
double max,min;
cv::imshow("p00",p00/255);
//
cv::minMaxIdx(p01,&min,&max);
cv::imshow("p01",(p01-min)/(max-min));
//
cv::minMaxIdx(p10,&min,&max);
cv::imshow("p10",(p10-min)/(max-min));
cv::minMaxIdx(p11,&min,&max);
cv::imshow("p11",(p11-min)/(max-min));
cv::minMaxIdx(p02,&min,&max);
cv::imshow("p02",(p02-min)/(max-min));
cv::minMaxIdx(p20,&min,&max);
cv::imshow("p20",(p20-min)/(max-min));
cv::waitKey();
#endif
dst.resize(7);
auto sigma_square = sigma*sigma;
auto p2d = p20-p02;
//LAM
dst[2] = sigma_square * (p20+p02);
//GAM
cv::sqrt( (p2d).mul(p2d) + (4.0f * p11.mul(p11)) ,dst[6] );
dst[6] = dst[6] * sigma_square;
//FLAT
dst[0] = eta*p00;
//slop
cv::sqrt(p10.mul(p10)+p01.mul(p01),dst[1]);
dst[1] *= 2.0f*sigma;
//blob dst[2]
dst[3] = -dst[2];
//line
dst[4] = pow(2.0,-0.5)*(dst[6]+dst[2]);
dst[5] = pow(2.0,-0.5)*(dst[6]-dst[2]);
//saddle dst[6]
#ifdef DISPLAY_WHILE_RUNNING
double max,min;
cv::minMaxIdx(dst[0],&min,&max);//
cv::imshow("FLAT",(dst[0]-min)/(max-min));
cv::minMaxIdx(dst[1],&min,&max);//
cv::imshow("SLOPE",(dst[1]-min)/(max-min));
cv::minMaxIdx(dst[2],&min,&max);
cv::imshow("BLOB+",(dst[2]-min)/(max-min));
cv::minMaxIdx(dst[3],&min,&max);//
cv::imshow("BLOB-",(dst[3]-min)/(max-min));
cv::minMaxIdx(dst[4],&min,&max);//
cv::imshow("LINE+",(dst[4]-min)/(max-min));
cv::minMaxIdx(dst[5],&min,&max);
cv::imshow("LINE-",(dst[5]-min)/(max-min));
cv::minMaxIdx(dst[6],&min,&max);
cv::imshow("SADDLE",(dst[6]-min)/(max-min));
cv::waitKey();
#endif
}
why dont you take average on dg and ddg?
cv::filter2D(gray,p20,CV_32FC1,g.t());
cv::filter2D(p20,p20,CV_32FC1,g.t());
why take two times of filter here?
//GAM
cv::sqrt( (p2d).mul(p2d) + (4.0f * p11.mul(p11)) ,dst[6] );
dst[6] = dst[6] * sigma_square;
where you get this formula ?