Sudoku Solver, small snippet issue (matlab) - matlab

For this little snippet, I am generating a random number, checking if it is part of the row and column, if it's not part of either, it inserts the number. I know it might put a number that is already in its 3x3 box, but that's a problem I can fix. Here's my snippet, if want my whole code I will edit. My whole code is around 100 lines.
% Find empty slots, generate random number 1 - 9, insert into slot.
for i=1:9
for j=1:9
number = board(i,j);
answer = ceil(9*rand(1,1));
row = board(i,:);
col = board(:,j);
if number==0 && (ismember(answer,row)==0) && (ismember(answer,col)==0)
board(i,j) = answer;
end
end
end
My problem, is when I ran this with a real unsolved puzzle, is
1) It inserted an 11 into a slot, how is that possible?
2) I still see rows and columns where there are more than one of the same number.
Thank you guys.

I don't know why your bit of code would result in duplicates on rows or columns and why you would see 11's, so this might not exactly be an answer to your question, but it might help you. I modified your code a bit, to not only try one random number, but try all numbers 1-9 (in random order):
for i=1:9
for j=1:9
tried = [];
while board(i,j)==0
newRand = 0;
while ~newRand
answer = ceil(9*rand);
if ~ismember(answer,tried)
newRand = 1;
end
end
row = board(i,:);
col = board(:,j);
if (ismember(answer,row)==0) && (ismember(answer,col)==0)
board(i,j) = answer;
else
tried = [tried answer];
if length(tried)==9
break;
end
end
end
end
end

Related

Filter data with standard derivation in loop

I have acceleration (10240x31) data that I want to filter by replacing every data point that exceeds the threshold value of 4 times standard derivation of each column with the mean value of the two adjacent data points.
First, I wanted to replace every data point with a zero, if it exceeds the maximum value. This is my loop:
for w = 1:31
Sigma(w) = std(zacceleration(:,w));
zacceleration(zacceleration<(-4*Sigma(w))) = 0;
zacceleration(zacceleration>(4*Sigma(w))) = 0;
end
That code works if w is just one number, for example:
w = 1;
But when w changes every iteration, the filtered data only contains the values that don't exceed the threshold value of the last dataset, Sigma(31).
So, I guess that I overwrite my data or something like that but I cant seem to find a solution.
Can anybody please give me a hint?
Thank you in advance and best regards.
I think I got it now.
Sigma = std(zacceleration);
for a = 1:10240;
for b = 1:31;
if zacceleration(a,b)<(-4*Sigma(b))
zacceleration(a,b) = 0;
end
if zacceleration(a,b)>(4*Sigma(b))
zacceleration(a,b) = 0;
end
end
end

Run the for loop only once Matlab

total_Route = zeros(4,4);
tmp = evalin('base', 't'); % i initialise t in the Workspace with the value 1
if(tmp==5)
tmp=1;
end
total_Route(tmp,1) = Distance_Traveled_CM;
total_Route(tmp,2) = Hauptantrieb_Verbrauchte_Energie_CM;
total_Route(tmp,3) = Nebenaggregate_Verbrauch_Real_CM;
total_Route(tmp,4) = t;
Total_Distance_Traveled_CM = sum(total_Route(:,1));
set(handles.edit3, 'string',Total_Distance_Traveled_CM);
Total_Hauptantrieb_Verbrauchte_Energie_CM = sum(total_Route(:,2));
set(handles.edit4, 'string',Total_Hauptantrieb_Verbrauchte_Energie_CM);
Total_Nebenaggregate_Verbrauch_Real_CM = sum(total_Route(:,3));
set(handles.edit5, 'string',Total_Nebenaggregate_Verbrauch_Real_CM);
%% Index
set(handles.edit15, 'string',tmp);
assignin('base', 't', tmp + 1); % with this line i can increment "t" after each pass
guidata(hObject,handles);
Sorry that I did not explain my problem well.
#Sardar_Usama I want to run the loop only once but t should be incremented after each time I click on my Button.
# Sembei Norimaki end is at the end of my codes, have forgotten to write it in my question
#Patrik & #Dennis Jaheruddin let me explain my problem again
I created a Matrix with 4×4 Elements with the Goal to save the results of each my Variable (Total_Distance_Traveled_CM, Total_Hauptantrieb_Verbrauchte_Energie_CM etc...) after each Simulation in the element of my Matrix (See image below).
I want by pressing a button (on my GUI) to get always the sum of each Column.
Example
The first pass: t = 1--> Distance_Traveled(1,1) is 900 the GUI will take through clicking on the Button, the sum of the first column (which is 900+0+0+0) and write it in a static test.
The second pass t = 2--> Distance_traveled(2,1) is 800 the GUI will take the sum of the first column (which is 900+800+0+0) and write it in a static test and the same thing should happen with the other column.
This should continue until t = 4 i.e. until it does the same thing for each column, then it should reset.
I hope, I have explained my problem better this time and I apologize for my bad English.
I appreciate any help.
Based on your code fragment the for loop is only called once.
However, the contents of the for loop are ran for four times. (first for i=1 then for 1=2 etc..)
If you only want to run one of these options the solution is very simple:
i = 1
yourLoopContent
If i is always 0 the first time, and you always want to run it for the current i, it would also be simple:
yourLoopContent
i = i+1;
However if i may not be set properly the first time, things get messy. This is because i is by default defined as the square root of minus 1.
Therefore I would recommend you to use a different letter like t instead. Then you could do this:
if ~exists(t)
t=0;
end
yourLoopContent %Everywhere using t instead of i
t = t+1;
In general you may want to avoid i as an index to stay clear of complex number issues.
I'm not sure if I got your question correctly, but it seems to me that what you look for is a cumulative sum. This can be done either buy summing on 1:t or by using cumsum. I'm not sure why you use a loop, but if this is only for the summing then cumsum can replace that.
Here is some example in your code:
total_Route = zeros(4,4);
% I commented below what is not part of the question
for t = 1:4
total_Route(t,:) = [Distance_Traveled_CM,
Hauptantrieb_Verbrauchte_Energie_CM,
Nebenaggregate_Verbrauch_Real_CM,
t];
% the following line compute the comulative sum from the top of each
% column to every element in it, so cs_total_Route(3,2) is like
% sum(total_Route(1:3,2)):
cs_total_Route = cumsum(total_Route);
Total_Distance_Traveled_CM = cs_total_Route(t,1); % OR sum(total_Route(1:t,1))
% set(handles.edit3, 'string',Total_Distance_Traveled_CM);
Total_Hauptantrieb_Verbrauchte_Energie_CM = cs_total_Route(t,2); % OR sum(total_Route(1:t,2))
% set(handles.edit4, 'string',Total_Hauptantrieb_Verbrauchte_Energie_CM);
Total_Nebenaggregate_Verbrauch_Real_CM = cs_total_Route(t,3); % OR sum(total_Route(1:t,3))
% set(handles.edit5, 'string',Total_Nebenaggregate_Verbrauch_Real_CM);
% set(handles.edit15, 'string',t);
end
And here is a quick look on what cumsum does (with some random numbers for total_Route):
total_Route =
671 4.6012 1.0662 1
840 3.6475 0.58918 2
354 8.6056 2.1313 3
893 4.1362 2.0118 4
cs_total_Route =
671 4.6012 1.0662 1
1511 8.2487 1.6554 3
1865 16.854 3.7867 6
2758 20.991 5.7985 10
Is this what you looked for?

how to select different sample in each loop from a population in matlab

i have a sequence
A = [1:5]
then i did its random permutation
B =perms(A);
C = B(randperm(size(B,1)), :)
then i select a random sample from the whole population with a 5 rows as follow
sample = C(1:5,1:5)
now i did my operation on each row in the sample,
now my problem occurs when i want to select a new sample from a population, but my code select the same sample again and again until my condition ends,
here is my code ,
clc
clear all
A=[1:5]
B=perms(A);
C = B(randperm(size(B,1)), :)
value_of_cmax = zeros(1,5);
for P=1:24
if P<= 24
sample = C(1:5,1:5)
sample_shuffled = sample(randperm(5),:)
below my operation on each row in sample
else
end
NOW if the loop goes again for second time, it takes again the sample sample.. not new. :(
This is because you're not updating the value of sample, and you're using the same value of sample again and again !
If I've understood your question correctly then this may help:
clc
clear all
A=[1:5]
B=perms(A);
value_of_cmax = zeros(1,5);
for P=1:24
C = B(randperm(size(B,1)), :);
sample = C(1:5,1:5)
if P<= 24
sample_shuffled = sample(randperm(5),:)
else end
end

Matlab programming code

I wrote a program on Matlab that checks how many numbers are divisable by 2 starting from 1 to integer N (that is set by the user)
Here's my code:
num=input('Please enter a number');
count=0;
while (num>=0);
if mod(num,2)==0;
count=count+1;
end
num=num-1;
end
disp(count)
I've tried to run this code but it doesn't output anything. I hope someone can help me figure out what is wrong it Please note that we haven't studied it in school, I just read online and tried to write something on my own.
I see many logical errors in your code. To begin with you are checking if num is divisible by 10, not 2. Also you should decrement num regardless if it passes the if condition, if you want to check the next number. Finally you say you want to check numbers ranging 1 to N but your while loop actually checks numbers 0 to N, due to the >= condition.
From a syntactical point of view: if's and while's (and for's) should not have a trailing semicolon after them.
So maybe something like this could be closer to what you are asking, albeit I still don't know if I fully understand your problem.
% Ask for user input
num = input('Please enter a number');
count = 0;
while (num > 0)
% Check for divisibility
if mod (num, 2) == 0
count = count + 1;
end
% Decrement number
num = num - 1;
end
% Display the count -- writing the variable name without an ending semicolon ';' causes Matlab to output the variable content
count
No need in loop, use Matlab the way it was designed for
num = input('Please enter a number ');
count = sum(mod(1 : num, 2) == 0);
disp(count);

How to can I count the number of ones?

The problem is:
In a class of 26 students, a test with 10 questions is given. The students answer the question by tossing a coin. I have to find out how many students have two or less answers correct. This is the program that I wrote, but I'm not sure about it ... is it good?
correct=0;
students=0;
for i=1:26
for j=1:10
answ=ceil(rand);
if answ==1
correct=correct+1;
if correct==2
students=students+1;
end
end
end
end
disp(students)
It's neater, faster to run, and more readable if you do it vectorized:
answers = round(rand(10,26)); % 10x26 matrix of 0 / 1 values
correct = sum(answers); % sum along each column
students = sum(correct<=2) % how many values of correct are 2 or less
By the way, from your code it appears you want to know how many students have 2 or more correct answers (not 2 or less as you state). In that case change last line to
students = sum(correct>=2) % how many values of correct are 2 or more
Slight modification to your code:
correct=0;
students=0;
for i=1:26
for j=1:10
answ=round(rand); % Use round instead of ceil
if (answ==1)
correct=correct+1;
if correct==2
students=students+1;
break;
end
end
end
correct=0; % Was missing in original code
end
disp(students)
Additional Note:
Try testing code for correct ans 5 as this will have more chances of variation to result because of uniform distribution of random number. Most of the students will get at-least 2 correct ans assuming equal probability, which is not the practical case.
Try maintaining habit of proper indentation. It will be more readable and less prone to errors.
Just like this : (You have to reset correct counter for every student, and some end aren't at the right place.)
correct = 0;
students = 0;
for i = 1:26
for j = 1:10
answ = ceil(rand);
if(answ==1)
correct = correct + 1;
end
end
if(correct < 2)
students = students + 1;
end
correct= 0;
end
EdIT
Sorry, I didn't saw the less in your sentense, so I change the > for <