plotting two functions on the same trendline in matlab - matlab

This is my original code:
function a = graph_times()
merge_times = [];
for i = 100:100:1000
curr = sort_timer(i);
merge_times = [merge_times, curr(1)];
end
plot(100:100:1000, merge_times);
a = 1;
end
I want to modify this code so that it plots trendlines for both insertion_sort and merge_sort on the same graph.
Below are the functions for merge_sort and insertion_sort
function c = insertion_sort(list1)
inserted = [];
for i = 1:size(list1,2)
inserted = insert_in_order(inserted,list1(1,i))
c = inserted
end
steps2=0;
function b = merge_sort(nums)
if size(nums,2) == 1
b = nums;
return;
end

You can give several sets of coordinates to MATLAB's plot function. You can plot the times of the two sorting algorithms like so:
plot(100:100:1000, merge_times, 100:100:1000, insertion_times);

Related

Convesion vector Index exceeds array bounds - matlab

I build some program in Matlab for "Histograma matching".
When I'm trying to implement the function "conVector" I get the error
"Index exceeds array bounds." anyone can help me with this error?
Here is my full code. Thank you!
function [newImage] = histShape (srcimg,destimg)
%find the histogram of the image
src = imgHist(srcimg);
dest = imgHist(destimg);
sna = normalizationHist(src);
dna = normalizationHist(dest);
conVector(sna,dna);
end
function [Hist] = imgHist (img)
[Rows,Cols] = size(img);
Hist = zeros(1,256);
for i=1:Rows
for j=1:Cols
Hist(img(i,j)+1)=Hist(img(i,j)+1)+1;
end
end
end
function [Ahist] = normalizationHist (hist)
[Rows,Cols] = size(hist);
Ahist = hist;
for i=2:256
Ahist(i)=Ahist(i-1)+hist(i);
end
Ahist = Ahist/(Rows*Cols);
end
function [cv] = conVector(SNA,DNA)
cv=zeros(1,257);
s = 1;
d = 1;
while s<=256
if DNA(d)<SNA(s)
d = d+1;
else
cv(s)=d;
s = s+1;
end
end
end
If all values in DNA(d:end) are smaller then the value in SNA(s) than the loop keep adding 1 to d but not to s, and finally goes out of bound because it conditioned only by s.
I guess you should either take the s = s+1 out of the inner condition, so it will be executed on every iteration, or add a condition on d to the loop, or convert it to a for loop.

Local Interest Point Detection using Difference of Gaussian in Matlab

I'm writing the code in Matlab to find interest point using DoG in the image.
Here is the main.m:
imTest1 = rgb2gray(imread('1.jpg'));
imTest1 = double(imTest1);
sigma = 0.6;
k = 5;
thresh = 3;
[x1,y1,r1] = DoG(k,sigma,thresh,imTest1);
%get the interest points and show it on the image with its scale
figure(1);
imshow(imTest1,[]), hold on, scatter(y1,x1,r1,'r');
And the function DoG is:
function [x,y,r] = DoG(k,sigma,thresh,imTest)
x = []; y = []; r = [];
%suppose 5 levels of gaussian blur
for i = 1:k
g{i} = fspecial('gaussian',size(imTest),i*sigma);
end
%so 4 levels of DoG
for i = 1:k-1
d{i} = imfilter(imTest,g{i+1}-g{i});
end
%compare the current pixel in the image to the surrounding pixels (26 points),if it is the maxima/minima, this pixel will be a interest point
for i = 2:k-2
for m = 2:size(imTest,1)-1
for n = 2:size(imTest,2)-1
id = 1;
compare = zeros(1,27);
for ii = i-1:i+1
for mm = m-1:m+1
for nn = n-1:n+1
compare(id) = d{ii}(mm,nn);
id = id+1;
end
end
end
compare_max = max(compare);
compare_min = min(compare);
if (compare_max == d{i}(m,n) || compare_min == d{i}(m,n))
if (compare_min < -thresh || compare_max > thresh)
x = [x;m];
y = [y;n];
r = [r;abs(d{i}(m,n))];
end
end
end
end
end
end
So there's a gaussian function and the sigma i set is 0.6. After running the code, I find the position is not correct and the scales looks almost the same for all interest points. I think my code should work but actually the result is not. Anybody know what's the problem?

How to vectorize a matlab script converting a 3d matrix to a single vector?

I am writing a graphical representation of numerical stability of differential operators and I am having trouble removing a nested for loop. The code loops through all entries in the X,Y, plane and calculates the stability value for each point. This is done by finding the roots of a polynomial of a size dependent on an input variable (length of input vector results in a polynomial 3d matrix of size(m,n,(lenght of input vector)). The main nested for loop is as follows.
for m = 1:length(z2)
for n = 1:length(z1)
pointpoly(1,:) = p(m,n,:);
r = roots(pointpoly);
if isempty(r),r=1e10;end
z(m,n) = max(abs(r));
end
end
The full code of an example numerical method (Trapezoidal Rule) is as follows. Any and all help is appreciated.
alpha = [-1 1];
beta = [.5 .5];
Wind = 2;
Wsize = 500;
if numel(Wind) == 1
Wind(4) = Wind(1);
Wind(3) = -Wind(1);
Wind(2) = Wind(4);
Wind(1) = Wind(3);
end
if numel(Wsize) == 1
Wsize(2) = Wsize;
end
z1 = linspace(Wind(1),Wind(2),Wsize(1));
z2 = linspace(Wind(3),Wind(4),Wsize(2));
[Z1,Z2] = meshgrid(z1,z2);
z = Z1+1i*Z2;
p = zeros(Wsize(2),Wsize(1),length(alpha));
for n = length(alpha):-1:1
p(:,:,(length(alpha)-n+1)) = alpha(n)-z*beta(n);
end
for m = 1:length(z2)
for n = 1:length(z1)
pointpoly(1,:) = p(m,n,:);
r = roots(pointpoly);
if isempty(r),r=1e10;end
z(m,n) = max(abs(r));
end
end
figure()
surf(Z1,Z2,z,'EdgeColor','None');
caxis([0 2])
cmap = jet(255);
cmap((127:129),:) = 0;
colormap(cmap)
view(2);
title(['Alpha Values (',num2str(alpha),') Beta Values (',num2str(beta),')'])
EDIT::
I was able to remove one of the for loops using the reshape command. So;
for m = 1:length(z2)
for n = 1:length(z1)
pointpoly(1,:) = p(m,n,:);
r = roots(pointpoly);
if isempty(r),r=1e10;end
z(m,n) = max(abs(r));
end
end
has now become
gg = reshape(p,[numel(p)/length(alpha) length(alpha)]);
r = zeros(numel(p)/length(alpha),1);
for n = 1:numel(p)/length(alpha)
temp = roots(gg(n,:));
if isempty(temp),temp = 0;end
r(n,1) = max(abs(temp));
end
z = reshape(r,[Wsize(2),Wsize(1)]);
This might be one for loop, but I am still going through the same number of elements. Is there a way to use the roots command on all of my rows at the same time?

Assign value to cell array through function MATLAB

I'm attempting to make a crude implementation of the AP CS 'gridworld' using matlab, albiet with fewer classes. So far I have a superclass 'Location' with the properties row and col. Next I have 'Grid' with just a cell array called grid. Using the Grid.get command, I can retrieve objects from that cell array. The problem though, is that I cannot get the Grid.put function to work. Testing without using the function allows me to put test strings into testGrid.grid{}, but the function doesn't seem to work.
classdef Location
properties
row;
col;
end
methods
%constructor, intializes with rows/columns
function loc = Location(r,c)
if nargin > 0
loc.row = r;
loc.col = c;
end
end
function r = getRow(loc)
r = loc.row;
end
function c = getCol(loc)
c = loc.col;
end
function display(loc)
disp('row: ')
disp(loc.row)
disp('col: ')
disp(loc.col)
end
end
Grid class, child of location:
classdef Grid < Location
properties
grid;
end
methods
function gr = Grid(rows, cols)
if nargin > 0
gr.grid = cell(rows,cols);
end
end
function nrows = getNumRows(gr)
[nrows,ncols] = size(gr.grid);
end
function ncols = getNumCols(gr)
[nrows,ncols] = size(gr.grid);
end
function put(gr,act,loc)
gr.grid{loc.getRow,loc.getCol} = act;
end
function act = get(gr,loc)
act = gr.grid{loc.getRow(),loc.getCol()};
end
end
Finally, the test commands from the command window
testLoc = Location(1,2)
row:
1
col:
2
testGrid = Grid(3,4)
row:
col:
testGrid.put('testStr',testLoc)
testGrid.get(testLoc)
ans =
[]
testGrid.grid{1,2} = 'newTest'
row:
col:
testGrid.get(testLoc)
ans =
newTest
Thanks for any insight!
You need to return the object from your functions and use that as your new object. So
function put(gr,act,loc)
gr.grid{loc.getRow,loc.getCol} = act;
end
Should be
function gr = put(gr,act,loc)
gr.grid{loc.getRow,loc.getCol} = act;
end
And then you can use it like
testGrid = Grid(3,4)
testGrid = testGrid.put(act, loc)
testGrid.get(loc)
And you can also chain the calls
testGrid.put(act, loc).get(loc)

Extract a value from MATLAB codistributed array

I am attempting to build a distributed array of handle class objects in MATLAB and I would like to extract a specific handle from this vector for use on the command line. Given the code below, I would like the following to execute. I am running this on with two labs (matlabpool 2). The getValue function is what I need assistance with, thanks...
vec = buildArray;
h = getValue(vec,6);
h.id
ClassA.m:
A class that I would like to distribute in parallel.
classdef ClassA < handle
properties
id;
end
methods
function obj = ClassA(id)
obj.id = id;
end
end
end
buildArray.m:
A function to build codistributed array from local instances of ClassA.
function vec = buildArray
X(:,1) = 1:10; % create ids
gsize = size(X); % the global size
X = distributed(X); % distribute the ids
spmd
x = getLocalPart(X); % extract the local ids
local = cell(length(x),1); % create local storage for handles
% Create the class instances
for i = 1:length(x);
local{i} = ClassA(x(i));
end
% Build the codistributed array of handles
codist = codistributor1d(codistributor1d.unsetDimension, ...
codistributor1d.unsetPartition, gsize);
vec = codistributed.build(local,codist);
end
getValue.m:
This is the function that I need help with, currently it just displays what lab that contains the class with the specified id. I would like for it to return the handle so it may be used from the command line. How is this done?
function h = getValue(vec, id)
h = []; % just so it will not throw an error
spmd
local = getLocalPart(vec);
for i = 1:length(local);
if local{i}.id == id;
% Export h here
disp(['ID ', num2str(id), ' is on lab ', num2str(labindex)]);
break;
end
end
end
I was able to get my problem working using this for getValue.m, is there a better way?
function h = getValue(vec, id)
spmd
local = getLocalPart(vec);
idx = [];
for i = 1:length(local);
if local{i}.id == id;
idx = i;
break;
end
end
codist = codistributor1d(codistributor1d.unsetDimension, ...
codistributor1d.unsetPartition, [numlabs,1]);
IDX = codistributed.build(idx, codist);
end
c = gather(vec(IDX));
h = c{1};