Matlab N-Queen Problem - matlab

main.m
counter = 1;
n = 8;
board = zeros(1,n);
back(0, board);
disp(counter);
sol.m
function value = sol(board)
for ( i = 1:(length(board)))
for ( j = (i+1): (length(board)-1))
if (board(i) == board(j))
value = 0;
return;
end
if ((board(i) - board(j)) == (i-j))
value = 0;
return;
end
if ((board(i) - board(j)) == (j-i))
value = 0;
return;
end
end
end
value = 1;
return;
back.m
function back(depth, board)
disp(board);
if ( (depth == length(board)) && (sol2(board) == 1))
counter = counter + 1;
end
if ( depth < length(board))
for ( i = 0:length(board))
board(1,depth+1) = i;
depth = depth + 1;
solv2(depth, board);
end
end
I'm attempting to find the maximum number of ways n-queen can be placed on an n-by-n board such that those queens aren't attacking eachother. I cannot figure out the problem with the above matlab code, i doubt it's a problem with my logic since i've tested out this logic in java and it seems to work perfectly well there. The code compiles but the issue is that the results it produces are erroneous.
Java Code which works:
public static int counter=0;
public static boolean isSolution(final int[] board){
for (int i = 0; i < board.length; i++) {
for (int j = i + 1; j < board.length; j++) {
if (board[i] == board[j]) return false;
if (board[i]-board[j] == i-j) return false;
if (board[i]-board[j] == j-i) return false;
}
}
return true;
}
public static void solve(int depth, int[] board){
if (depth == board.length && isSolution(board)) {
counter++;
}
if (depth < board.length) { // try all positions of the next row
for (int i = 0; i < board.length; i++) {
board[depth] = i;
solve(depth + 1, board);
}
}
}
public static void main(String[] args){
int n = 8;
solve(0, new int[n]);
System.out.println(counter);
}

Worked code:
function queen
clc;
counter = 0;
n = 8;
board = zeros(1,n);
[board,counter] = back(1, board,counter);
fprintf('Solution count: %d\n',counter);
%%
function value = isSolution(board)
for i = 1:length(board)
for j = (i+1): length(board)
if abs(board(i) - board(j)) == abs(i-j)
value = false;
return;
end
end
end
value = true;
%%
function [board,counter] = back(depth, board,counter)
if (depth == length(board)+1) && isSolution(board)
counter = counter + 1;
disp(board);
end
if ( depth <= length(board))
for i = 1:length(board)
if ~any(board==i)
board(1,depth) = i;
[~,counter] = back(depth+1, board,counter);
end
end
end
I add line if ~any(board==i), without this check, I think your java solution slower than this Matlab code. For fastest solution google "Dancing links".

There are many problems with your code.
Here are just a few:
you initialize board as 1-by-8 array
you call functions sol2 and solv2 that are undefined
no output is captured for solv2, or back (remember, Matlab passes variables by value, not by reference)
there are no comments in the code that would explain what you think you're doing and why you'd want to do that.
Also: While Matlab has a JIT compiler that, among others, helps speed up loops, Matlab code can't be said to "compile" (unless you're doing something dramatically wrong).

Related

I'm trying to simulate the Monty Hall problem in Matlab. What am I doing wrong?

As stated in title. I know that the probability of winning if one swaps doors in this problem should be roughly 66% but I seem to get answers implying a 33% success rate in cases where the player swaps as well as where the player does not swap. The variables associated with these two values are swapwinratio and noswapwinratio and these both consistently return values of roughly 0.33 at runtime. In tests, I've run sample numbers of 5000 to 10,000. Here is my code:
clc; clear all; close all;
numsamps = input("Enter number of samples to take. \n");
if(mod(numsamps, 1) || numsamps < 1)
error("Must be a positive integer number.");
end
wins = 0;
swapwins = 0;
noswapwins = 0;
swaps = 0;
noswaps = 0;
for i = 1:numsamps
doors = 1:3;
host = ceil(3 * rand());
player = ceil(3 * rand());
p1 = player;
doors(player) = 0;
goat = ceil(2 * rand());
for j = goat:3
if(doors(j) ~= 0)
doors(j) = 0;
break;
end
end
swap = floor(2 * rand());
if(swap)
ind = find(doors ~= 0);
player = doors(ind);
swaps = swaps + 1;
else
noswaps = noswaps + 1;
end
if(player == host)
wins = wins + 1;
if(swap)
swapwins = swapwins + 1;
else
noswapwins = noswapwins + 1;
end
end
end
swapwinratio = swapwins/swaps;
noswapwinratio = noswapwins/noswaps;
Sorry if I've missed anything; this is my first time posting to stackoverflow!

Matlab to openCV code conversion

I am trying to convert a code in MatLab to OpenCV but I am stuck about the following lines as I don't know much programming
MatLab code:
[indx_row, indx_col] = find(mask ==1);
Indx_Row = indx_row;
Indx_Col = indx_col;
for ib = 1:nB;
istart = (ib-1)*n + 1;
iend = min(ib*n, N);
indx_row = Indx_Row(istart:iend);
indx_col = Indx_Col(istart:iend);
openCV code:
vector <Point> index_rowCol;
for(int i=0; i<mask.rows; i++)
{
for(int j=0; j<mask.cols; j++)
{
if( mask.at<float>(i,j) == 1 )
{
Point pixel;
pixel.x = j;
pixel.y = i;
index_rowCol.push_back(pixel);
}
}
}
//Code about the "for loop" in MatLab code
for(int ib=0 ; ib<nB; ib++)
{
int istart = (ib-1)*n;
int iend = std::min( ib*n, N );
index_rowCol.clear();// Clearing the "index_rowCol" so that we can fill it again from "istart" to "iend"4
for(int j = istart; j<iend; j++)
{
index_rowCol.push_back( Index_RowCol[j] );
}
}
I am unable to understand if it is ok or not?
I think that there is mistake in usage of min function.
Here
for ib = 1:nB;
istart = (ib-1)*n + 1;
iend = min(ib*n, N);
ib - is array [1,2,3..nB] and you compare each value with N. As the result you also get array.
So as result:
ib - is array, istart - is array and iend also an array.
In C++ implementation
for(int ib=0 ; ib<nB; ib++)
{
int istart = (ib-1)*n;
int iend = std::min( ib*n, N );
you work with scalars (here ib,istars and iend are scalars).
For better understand how the code above works use step-by-step debugging. (Set breakpoint and run the code then press (F10 key-for matlab) )

How to implement priority queue in matlab

Is there any library in matlab that provides the functionality of min priorityqueue
import java.util.PriorityQueue;
import java.util.*;
public class MyQueue {
Comparator<Double> c;
PriorityQueue<Double> PQ;
public MyQueue() {
c = new Comparator<Double>(){
public int compare(Double o1, Double o2){
if(o2 > o1) {
return -1;
} else if(o1 > o2) {
return 1;
} else {
return 0;
}
}
};
PQ = new PriorityQueue<Double>(1000,c);
}
public void addElement(double d) {
PQ.add(d);
}
public double removeElement() {
return(PQ.remove());
}
}
I have implemented this priorty queue in java. I can call it from matlab. However, I need to associate each cost with an index. I mean it's not only cost of the node that i need to store but also its index. How can I accomplish this. I need to pass the index from matlab
You can use Java's default PriorityQueue like so:
>> q=java.util.PriorityQueue;
>> q.add({value,index});
This is available since Java ≥ 1.5, which is pre-bundled in all MATLAB releases since 7.0.4 (R14).
Otherwise, you can use the one from the file exchange, which you'll have to compile.
There's also a Simulink block for it, but I doubt that's what you're after.
Below is a resizing-array implementation of a priority queue written entirely in matlab. You can attach/couple any kind of data/index you want along with the priority value. Also, you can switch/toggle the behaviour between a min and max priority queue through a boolean argument passed into the constructor when it is created.
classdef PriorityQueue < handle
properties (SetAccess = private)
numElements;
priorityList;
valueList;
flagMaxPriorityQueue;
end
methods (Access = public)
function obj = PriorityQueue( flagMaxPriorityQueue )
if ~exist( 'flagMaxPriorityQueue', 'var' )
flagMaxPriorityQueue = true;
else
if ~(isscalar(flagMaxPriorityQueue) && islogical(flagMaxPriorityQueue))
error( 'ERROR: invalid flagMaxPriorityQueue argument' );
end
end
obj.flagMaxPriorityQueue = flagMaxPriorityQueue;
obj.numElements = 0;
obj.priorityList = {};
obj.valueList = {};
end
function insert(obj, priority, value)
% increase the size of the array if full
if obj.numElements > 0 && obj.numElements + 1 > numel( obj.priorityList )
% double the size of the array and copy stuff
obj.priorityList = cat(1, obj.priorityList, cell(obj.numElements, 1));
obj.valueList = cat(1, obj.valueList, cell(obj.numElements, 1));
end
obj.numElements = obj.numElements + 1;
obj.priorityList{ obj.numElements } = priority;
obj.valueList{ obj.numElements } = value;
obj.swim(obj.numElements);
end
function [priority, value] = pop( obj )
if obj.isEmpty()
error( 'called pop() on an empty priority queue' );
end
priority = obj.priorityList{1};
value = obj.valueList{1};
obj.exch(1, obj.numElements);
obj.numElements = obj.numElements - 1;
obj.sink(1);
obj.priorityList{ obj.numElements + 1 } = [];
obj.valueList{ obj.numElements + 1 } = [];
% halve the size of the arrays if they get one-quarter full
if obj.numElements > 0 && obj.numElements == floor( numel( obj.priorityList ) / 4 )
obj.priorityList( 2 * obj.numElements + 1 : end ) = [];
obj.valueList( 2 * obj.numElements + 1 : end ) = [];
end
end
function [flagEmpty] = isEmpty( obj )
flagEmpty = (obj.numElements == 0);
end
function [qSize] = size( obj )
qSize = obj.numElements;
end
function [priority, value] = peek( obj )
if obj.isEmpty()
error( 'requested max() of an empty priority queue' );
end
priority = obj.priorityList{1};
value = obj.valueList{1};
end
end
methods (Access = private)
function swim(obj, elPos)
while elPos > 1 && obj.compare(floor(elPos / 2), elPos)
obj.exch(floor(elPos / 2), elPos);
elPos = floor(elPos / 2);
end
end
function sink(obj, elPos)
while 2 * elPos <= obj.numElements
j = 2 * elPos;
if j < obj.numElements && obj.compare(j, j+1)
j = j + 1;
end
if ~obj.compare(elPos, j)
break;
end
obj.exch(elPos, j);
elPos = j;
end
end
function [blnCmpResult] = compare(obj, e1, e2)
if obj.flagMaxPriorityQueue
blnCmpResult = (obj.priorityList{e1} < obj.priorityList{e2});
else
blnCmpResult = (obj.priorityList{e1} > obj.priorityList{e2});
end
end
function exch(obj, e1, e2 )
temp = obj.priorityList{e1};
obj.priorityList{e1} = obj.priorityList{e2};
obj.priorityList{e2} = temp;
temp = obj.valueList{e1};
obj.valueList{e1} = obj.valueList{e2};
obj.valueList{e2} = temp;
end
end
end % classdef

Porting signal windowing code from Matlab to Java

This is part of a code from spectral subtraction algorithm,i'm trying to optimize it for android.please help me.
this is the matlab code:
function Seg=segment(signal,W,SP,Window)
% SEGMENT chops a signal to overlapping windowed segments
% A= SEGMENT(X,W,SP,WIN) returns a matrix which its columns are segmented
% and windowed frames of the input one dimentional signal, X. W is the
% number of samples per window, default value W=256. SP is the shift
% percentage, default value SP=0.4. WIN is the window that is multiplied by
% each segment and its length should be W. the default window is hamming
% window.
% 06-Sep-04
% Esfandiar Zavarehei
if nargin<3
SP=.4;
end
if nargin<2
W=256;
end
if nargin<4
Window=hamming(W);
end
Window=Window(:); %make it a column vector
L=length(signal);
SP=fix(W.*SP);
N=fix((L-W)/SP +1); %number of segments
Index=(repmat(1:W,N,1)+repmat((0:(N-1))'*SP,1,W))';
hw=repmat(Window,1,N);
Seg=signal(Index).*hw;
and this is our java code for this function:
public class MatrixAndSegments
{
public int numberOfSegments;
public double[][] res;
public MatrixAndSegments(int numberOfSegments,double[][] res)
{
this.numberOfSegments = numberOfSegments;
this.res = res;
}
}
public MatrixAndSegments segment (double[] signal_in,int samplesPerWindow, double shiftPercentage, double[] window)
{
//default shiftPercentage = 0.4
//default samplesPerWindow = 256 //W
//default window = hanning
int L = signal_in.length;
shiftPercentage = fix(samplesPerWindow * shiftPercentage); //SP
int numberOfSegments = fix ( (L - samplesPerWindow)/ shiftPercentage + 1); //N
double[][] reprowMatrix = reprowtrans(samplesPerWindow,numberOfSegments);
double[][] repcolMatrix = repcoltrans(numberOfSegments, shiftPercentage,samplesPerWindow );
//Index=(repmat(1:W,N,1)+repmat((0:(N-1))'*SP,1,W))';
double[][] index = new double[samplesPerWindow+1][numberOfSegments+1];
for (int x = 1; x < samplesPerWindow+1; x++ )
{
for (int y = 1 ; y < numberOfSegments + 1; y++) //numberOfSegments was 3
{
index[x][y] = reprowMatrix[x][y] + repcolMatrix[x][y];
}
}
//hamming window
double[] hammingWindow = this.HammingWindow(samplesPerWindow);
double[][] HW = repvector(hammingWindow, numberOfSegments);
double[][] seg = new double[samplesPerWindow][numberOfSegments];
for (int y = 1 ; y < numberOfSegments + 1; y++)
{
for (int x = 1; x < samplesPerWindow+1; x++)
{
seg[x-1][y-1] = signal_in[ (int)index[x][y]-1 ] * HW[x-1][y-1];
}
}
MatrixAndSegments Matrixseg = new MatrixAndSegments(numberOfSegments,seg);
return Matrixseg;
}
public int fix(double val) {
if (val < 0) {
return (int) Math.ceil(val);
}
return (int) Math.floor(val);
}
public double[][] repvector(double[] vec, int replications)
{
double[][] result = new double[vec.length][replications];
for (int x = 0; x < vec.length; x++) {
for (int y = 0; y < replications; y++) {
result[x][y] = vec[x];
}
}
return result;
}
public double[][] reprowtrans(int end, int replications)
{
double[][] result = new double[end +1][replications+1];
for (int x = 1; x <= end; x++) {
for (int y = 1; y <= replications; y++) {
result[x][y] = x ;
}
}
return result;
}
public double[][] repcoltrans(int end, double multiplier, int replications)
{
double[][] result = new double[replications+1][end+1];
for (int x = 1; x <= replications; x++) {
for (int y = 1; y <= end ; y++) {
result[x][y] = (y-1)*multiplier;
}
}
return result;
}
public double[] HammingWindow(int size)
{
double[] window = new double[size];
for (int i = 0; i < size; i++)
{
window[i] = 0.54-0.46 * (Math.cos(2.0 * Math.PI * i / (size-1)));
}
return window;
}
"Porting" Matlab code statement by statement to Java is a bad approach.
Data is rarely manipulated in Matlab using loops and addressing individual elements (because the Matlab interpreter/VM is rather slow), but rather through calls to block processing functions (which have been carefully written and optimized). This leads to a very idiosyncratic programming style in which repmat, reshape, find, fancy indexing et al. are used to do operations which would be much more naturally expressed through Java loops.
For example, to multiply each column of a matrix A by a vector v, you will write in matlab:
A = diag(v) * A
or
A = repmat(v', 1, size(A, 2)) .* A
This solution:
for i = 1:size(A, 2),
A(:, i) = A(:, i) .* v';
end;
is inefficient.
But it would be terribly foolish to try to do the same thing in Java and invoke a matrix product or to build a matrix with repeated copies of v. Instead, just do:
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
a[i][j] *= v[i]
}
}
I suggest you to try to understand what this matlab function is actually doing, instead of focusing on how it is doing it, and reimplement it from scratch in Java, forgetting all the matlab implementation except the specifications given in the comments. Half of the code you have written is useless, indeed. Actually, it seems to me that this function wouldn't be needed at all, and what it does could be efficiently integrated in the caller's code.

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.