While loop keeps going even though creteria has been met - matlab

Hello I need this count to stop once my variable 'fourMil' is <= o but the loop keeps going and IDK why. Some help would be appreciated.
% Sum of the Fibonacci pair numbers until 4 million
clc
clear
fibo_list = [];
for i = (0:31)
if (i == 0 || i == 1 || i == 2)
fibo_list(end+1) = i + 1;
else
fibo_list(end+1) = fibo_list(end) + fibo_list(end-1);
end
end
filtered_list = [];
fourMil = 4000000;
while fourMil > 0
for i = fibo_list
if mod(i,2) == 0
filtered_list(end+1) = i;
fourMil = fourMil - filtered_list(end);
end
end
end
sumation = sum(filtered_list);
fprintf('the sum of the Fibo numbers is %i\n', sumation)

You can use a break statement to break the while loop when a condition is met:
while fourMil > 0
for i = fibo_list
if mod(i,2) == 0
filtered_list(end+1) = i;
if (fourMil - filtered_list(end)<0)
break; %This will break the loop
end
fourMil = fourMil - filtered_list(end)
end
end
end

Related

Diagonals in winning conditions in connect four program are not working correctly and I do not know why

My winning conditions for rows and columns works completely fine. However, my diagonals do not. It will say you have won if you get your own number in 4 different rows and not in a direct diagonal as the game is meant to be played.
%check if won by columns
for column = 1:7
counter = 0;
for row = 1:6
if(board(row,column) == players(1,2))
counter = counter + 1;
if(counter == 4)
fprintf('You win! \n')
break
end
else
counter = 0;
end
end
end
%check if won by rows
for row = 1:6
counter = 0;
for column = 1:7
if(board(row, column) == players(1,2))
counter = counter + 1;
if(counter == 4)
fprintf('You win! \n')
break
end
else
counter = 0;
end
end
end
%check if won by diagonal \ 1
for column = 1:4
for row = 1:3
counter = 0;
if(board(row, column) == players(1))
counter = (row+1), (column+1), (row+2), (column+2), (row+3), (column+3);
if(counter == 4)
fprintf('You win! \n')
break
end
else
counter = 0;
end
end
end
%check if won by diagonal / 1
for column = 7:-1:4
for row = 1:3
counter = 0;
if(board(row, column) == players(1))
counter = (row+1), (column-1), (row+2), (column-2), (row+3), (column-3);
if(counter == 4)
fprintf('You win! \n')
break
end
else
counter = 0;
end
end
end

Matlab Prime number list checker

Ok so I have been having a go at creating a prime number checker. I have been successful in making it work for a specific number. The code is here.
#To test if number is prime
prompt = input("number to test if prime: ");
n = prompt;
i = 2; #start of mod test
t = floor(sqrt(n));
counter = 0;
tic
for i = 2:t
if mod(n,i) == 0
disp('n is not prime')
break
else
counter = (counter + 1);
end
end
if counter == t-1
disp('n is prime')
end
toc
I then tried to make a program which would test a range of numbers. It's been successful for n=10, but when I go higher than that it doesn't seem to pick up the primes. I'm not sure where I'm going wrong.
#Want to test numbers 2:n if they're prime
prompt = input("max number to test: ");
n = prompt;
l = 2; #start of mod test
counter = 0;
tic
for i = 2:n #cycle to test 2 up to n
t = floor(sqrt(i)) #Only need to test up to root of number
for l = 2:t
if mod(i,l) == 0
break
else
counter = (counter + 1);
end
end
if counter == t-1 # if tested up to the root of the number, it must be prime
prime = sprintf('%d is prime', round(i));
disp(prime)
counter = 0;
end
end
toc
Any help in getting it to work for larger values would be greatly appreciated and also any ways to make the code more efficient. The top program can test 982451653 in 0.268 seconds on my laptop.
Just a way to linearize your algorithm:
n = 997 %test number
t1 = n./([2,3:2:n/2]);
t2 = t1 - round(t1);
res = sum(t2 == 0); %can n be divided ?
if res == 0
fprintf('%s','prime');
else
fprintf('%s','not prime');
end
I got help on the issue and found that 'counter' was constantly re-setting and needed to be moved up. Fixed code is here
#Want to test numbers 2:n if they're prime
prompt = input("max number to test: ");
n = prompt;
l = 2; #start of mod test
counter = 0;
tic
for i = 2:n #cycle to test 2 up to n
t = floor(sqrt(i)); #Only need to test up to root of number
counter = 0;
for l = 2:t
if mod(i,l) == 0
break
else
counter = (counter + 1);
end
end
if counter == t-1; # if tested up to the root of the number, it must be prime
prime = sprintf('%d is prime', round(i));
disp(prime)
end
end
toc

Matlab coder "Error indenting generated C code"

I am Trying to convert a MATLAB code to C++ using MATLAB coder but this error apears:
Error indenting generated C code
The error points to the name of the function itself and has no more explanations in it. can someone tell me what is this error?
here is the function i want to conver:
function [Report_Clustered,ClusterCounter_new]=InitClusterGenerator_test(Report_In,~,FreqEpsilon,DegreeEpsilon,~,ClusterCounter_old, BlockCount, Report_old)
Report_M = zeros(size(Report_In,1),size(Report_In,2),4);
for i=1:size(Report_In,1)
for j=1:size(Report_In,2)
Report_M(i,j,1)=Report_In(i,j,1);
Report_M(i,j,2)=Report_In(i,j,2);
Report_M(i,j,3)=0; % Cluster number that the point belongs to.
Report_M(i,j,4)=0;
Report_In{i,j}
end
end
ClusterCounter = 0;
for i=1:size(Report_M,1)
for j=1:size(Report_M,2)
if (Report_M(i,j,3) == 0)
ClusterCounter = ClusterCounter + 1;
Report_M(i,j,3) = ClusterCounter;
for ii=1:size(Report_M,1)
for jj=1:size(Report_M,2)
if (Report_M(ii,jj,3) == 0)
if (abs(Report_M(i,j,1)-Report_M(ii,jj,1))<FreqEpsilon &&...
(abs(Report_M(i,j,2)-Report_M(ii,jj,2)) <DegreeEpsilon ||...
abs(-360 + Report_M(i,j,2)-Report_M(ii,jj,2)) <DegreeEpsilon ||...
abs(360 + Report_M(i,j,2)-Report_M(ii,jj,2)) <DegreeEpsilon))
Report_M(ii,jj,3) = ClusterCounter;
end
end
end
end
end
end
end
if (BlockCount> 20 && ClusterCounter<4)
warning = 1;
end
ClusterCounter_new = ClusterCounter;
%clear Report_new;
flag = 0;
Report_new = zeros(ClusterCounter,size (Report_M, 2),4);
index = zeros(1, ClusterCounter_new);
for i = 1: size (Report_M, 1)
for j = 1: size (Report_M, 2)
for k = 1: ClusterCounter_new
if (Report_M(i,j,3) == k)
index(1,k) = index(1,k) + 1;
Report_new(k,index(1,k), 1:3) = Report_M(i,j,1:3);
flag = flag + 1;
end
end
end
end
for j = 1: size (Report_new, 2)
for i = 1: size (Report_new, 1)
if (Report_new(i,j,1) == 0)
Report_new(i,j,1:3) = Report_new(i,1,1:3);
end
end
end
%Report_new = Report;
MedoidF_old = zeros(1, size(Report_old,1));
MedoidA_old = zeros(1, size(Report_old,1));
for i=1:size(Report_old,1)
SumF = 0;
SumA = 0;
MinAngle = 361;
MaxAngle = -1;
for j=1:size(Report_old,2)
SumF = SumF + Report_old(i,j,1);
SumA = SumA + Report_old(i,j,2);
if Report_old(i,j,2) > MaxAngle
MaxAngle = Report_old(i,j,2);
elseif Report_old(i,j,2) < MinAngle
MinAngle = Report_old(i,j,2);
end
end
MedoidF_old(1, i) = SumF/size(Report_old,2);
if (MaxAngle - MinAngle) > 350
MedoidA_old(1, i) = 0;
else
MedoidA_old(1, i) = SumA/size(Report_old,2);
end
end
MedoidF_new = zeros(1, size(Report_new,1));
MedoidA_new = zeros(1, size(Report_new,1));
for i=1:size(Report_new,1)
SumF = 0;
SumA = 0;
MinAngle = 361;
MaxAngle = -1;
for j=1:size(Report_new,2)
SumF = SumF + Report_new(i,j,1);
SumA = SumA + Report_new(i,j,2);
if Report_new(i,j,2) > MaxAngle
MaxAngle = Report_new(i,j,2);
elseif Report_new(i,j,2) < MinAngle
MinAngle = Report_new(i,j,2);
end
end
MedoidF_new(1, i) = SumF/size(Report_new,2);
if (MaxAngle - MinAngle) > 350
MedoidA_new(1, i) = 0;
else
MedoidA_new(1, i) = SumA/size(Report_new,2);
end
end
TempCluster = zeros(1, size(Report_new, 1));
CurrentCluster = ClusterCounter_old;
for i = 1: 1: size(Report_new,1)
for j = 1: 1: size(Report_old,1)
if (abs(MedoidF_old(1,j)-MedoidF_new(1,i))<FreqEpsilon &&...
(abs(MedoidA_old(1,j)-MedoidA_new(1,i))<DegreeEpsilon ||...
abs(360 + MedoidA_old(1,j)-MedoidA_new(1,i))<DegreeEpsilon ||...
abs(-360 + MedoidA_old(1,j)-MedoidA_new(1,i))<DegreeEpsilon)) %%if the new cluster is the rest of an old cluster use the old one's index for it
TempCluster(1,i) = Report_old(j,1,3);
end
end
%%this part is for seperating the clusters which where in the collision state in the past time
if (TempCluster(1,i)>0) %%if the new cluster is one of the old ones the index should be set
for j = 1:1:size(Report_new, 2)
Report_new(i,j,3) = TempCluster(1,i);
Report_new(i,j,4) = 1;% Alive
end
else %%first search if the new cluster is a part of a newly found cluster found before this one
for j = 1: 1: i-1
if (abs(MedoidF_new(1,j)-MedoidF_new(1,i))<FreqEpsilon &&...
(abs(MedoidA_new(1,j)-MedoidA_new(1,i))<DegreeEpsilon ||...
abs(360 + MedoidA_new(1,j)-MedoidA_new(1,i))<DegreeEpsilon ||...
abs(-360 + MedoidA_new(1,j)-MedoidA_new(1,i))<DegreeEpsilon)) %%if the new cluster is the rest of an old cluster use the old one's index for it
TempCluster(1,i) = Report_new(j,1,3);
end
end
end
if (TempCluster(1,i)>0) %%if the new cluster is one of the old ones the index should be set
for j = 1:1:size(Report_new, 2)
Report_new(i,j,3) = TempCluster(1,i);
Report_new(i,j,4) = 1;% Alive
end
else %%new cluster is just began so it needs a new index
CurrentCluster = CurrentCluster + 1;
ClusterCounter_new = CurrentCluster;
TempCluster(1,i) = CurrentCluster;
for j = 1:1:size(Report_new, 2)
Report_new(i,j,3) = TempCluster(1,i);
Report_new(i,j,4) = 1; % Alive
end
end
end
NewClusters = zeros(1, size (Report_new, 1));
for i = 1: size(Report_new, 1)
NewClusters (1,i) = Report_new(i,1,3);
end
OldClusters = zeros(1, size (Report_old, 1));
OldClustersLine = zeros(1, size (Report_old, 1));
for i = 1: size(Report_old, 1)
OldClusters (1,i) = Report_old(i,1,3);
OldClustersLine (1, i) = i;
end
NumberOfDead = 0;
%clear AddDead;
AddDead = zeros (16,size(Report_new, 2),4);
if (BlockCount>10)
for i = 1: size (OldClusters, 2)
IsDead = 1;
for j = 1: size (NewClusters, 2)
if OldClusters(1, i) == NewClusters(1,j)
IsDead = 0;
end
end
if (IsDead == 1)
NumberOfDead = NumberOfDead + 1;
%clear TempLine;
TempLine = zeros(1, size(Report_old,2), 4);
TempLine(1,:,1:3) = Report_old(OldClustersLine(1, i),:,1:3);
for k= 1: size(TempLine, 2)
TempLine(1,k,4) = 0; % Dead
end
TempSize = size(TempLine, 2);
Thresh = size(Report_new, 2);
if (TempSize >= Thresh)
AddDead (NumberOfDead, 1:Thresh, 1:4) = TempLine(1,1:Thresh, 1:4);
else
for l = 1: Thresh-TempSize
TempLine(1, TempSize+l, 1:4) = TempLine(1, TempSize, 1:4);
end
AddDead (NumberOfDead, 1:Thresh, 1:4) = TempLine(1,1:Thresh, 1:4);
end
end
end
xR = size (Report_new,1);
if (NumberOfDead == 0)
Report_Clustered = zeros (size(Report_new,1),size(Report_new,2),size(Report_new,3));
else
Report_Clustered = zeros (size(Report_new,1) + NumberOfDead,size(Report_new,2),size(Report_new,3));
end
Report_Clustered (1:size(Report_new,1), :, :) = Report_new(:,:,:);
for i = 1: NumberOfDead
Report_Clustered(xR + i, :) = AddDead(i, :);
end
end
and I'm using matlab 2012a
Tnx.
From what you've said in the comments, it appears that you simply need to call
clear functions
from the command line before recompiling the function to allow Matlab to overwrite the files. See this Matlab forum or the documentation for clear for more detail.

Matlab Reversi 'valid move' check

Having issues with my move checker currently, it seems that the failsafe I put in my code to make it not look outside the bounds of the matrix isn't working, any suggestions?
There is also the issue that it doesn't seem to be working (i.e. I am still able to place pieces wherever I want!). The code I use earlier up is listed below as well
code:
function legal = legalMove()
d_l = [0, -1];
d_r = [0, 1];
d_u = [-1, 0];
d_d = [1, 0];
d_ul = [-1, -1];
d_ur = [-1, 1];
d_dl = [1, -1];
d_dr = [1, 1];
directions = {'d_l' 'd_ul' 'd_u' 'd_ur' 'd_r' 'd_dr' 'd_d' 'd_dl'};
valid_moves = zeros(8,8);
for ci = 1:8
for cj = 1:8
if game_state(ci,cj) == 0 %check element = 0
for count = 1:8
d = eval( directions{count} );
ti = ci+d(1);
tj = cj+d(2);
% Check if out of the board
if (ti > 8 || ti < 1) || (tj > 8 || tj < 1)
break
else
% Number of enemy pieces you went over
cnt = 0;
selected = game_state(ti, tj);
% Move while going over enemy pieces
while selected == player_number * -1
ti = ti + d(1);
tj = tj + d(2);
selected = game_state(ti, tj);
% Check if out of the board
if (ti > 8 || ti < 1) || (tj > 8 || tj < 1)
break
else
end
% Count pieces you went over
cnt = cnt + 1;
end
end
% Check if you moved over enemy pieces & whether you landed on your piece
if selected == player_number
valid_moves(ti,tj) = 1;
else
end
end
else
end
end
end
if ~isempty(valid_moves)
legal = 1;
else
legal = 0;
end
end
Error returned when done # boundries:
Attempted to access game_state(0,7); index must be a positive integer or
logical.
Error in umpire/legalMove (line 217)
selected = game_state(ti, tj);
Error in umpire/buttonPress (line 85)
legal = legalMove();
other piece:
function buttonPress(hObject, eventdata)
ended = game_is_over();
if ended == 1;
setAllInactive();
winner = calc_winner();
if winner == -1;
set(stat_text,'string','Winner is White! Restart?')
elseif winner == 1;
set(stat_text,'string','Winner is Black! Restart?')
else
set(stat_text,'string','Game is a tie! Restart?')
end
else
end
legal = legalMove();
if legal ~= 1;
set(stat_text,'Illegal move! Try again')
return
else
end
game_state(get(hObject,'userdata')) = player_number;
drawScreen();
player_number = player_number * -1;
end
In the second place where you assign variable selected (near the end of the function legalMove), you have out-of-board check in the wrong place.
Here's a fixed version
% ...
% Number of enemy pieces you went over
cnt = 0;
selected = game_state(ti, tj);
% Move while going over enemy pieces
while selected == player_number * -1
ti = ti + d(1);
tj = tj + d(2);
% Check if out of the board
if (ti > 8 || ti < 1) || (tj > 8 || tj < 1)
break
else
end
selected = game_state(ti, tj);
% Count pieces you went over
cnt = cnt + 1;
end
end
% Check if you moved over enemy pieces & whether you landed on your piece
if selected == player_number
valid_moves(ti,tj) = 1;
else
end
end

Matlab error : Subscript indices must either be real positive integers or logicals

I have the following error in MATLAB:
??? Subscript indices must either be real positive integers or
logicals.
Error in ==> Lloyd_Max at 74 D(w_count) = mean((x -
centers(xq)).^2);
This is my code :
function [ xq,centers,D ] = Lloyd_Max( x,N,min_value,max_value )
%LLOYD_MAX Summary of this function goes here
% Detailed explanation goes here
x = x';
temp = (max_value - min_value)/2^N;
count=1;
for j=0:temp:((max_value - min_value)-temp),
centers(count) = (j + j + temp )/2;
count = count + 1;
end
for i=1:length(centers),
k(i) = centers(i);
end
w_count = 0;
while((w_count < 2) || (D(w_count) - D(w_count - 1) > 1e-6))
w_count = w_count + 1;
count1 = 2;
for i=2:(count-1),
T(i) = (k(i-1) + k(i))/2;
count1 = count1 +1 ;
end
T(1) = min_value;
T(count1) = max_value;
index = 1;
for j=2:count1,
tempc = 0;
tempk = 0;
for k=1:10000,
if(x(k) >= T(j-1) && x(k) < T(j))
tempk = tempk + x(k);
tempc = tempc + 1;
end
end
k(index) = tempk;
k_count(index) = tempc;
index = index + 1;
end
for i=1:length(k),
k(i) = k(i)/k_count(i);
end
for i=1:10000,
if (x(i) > max_value)
xq(i) = max_value;
elseif (x(i) < min_value)
xq(i) = min_value;
else
xq(i) = x(i);
end
end
for i=1:10000,
cnt = 1;
for l=2:count1,
if(xq(i) > T(l-1) && xq(i) <= T(l))
xq(i) = cnt;
end
cnt = cnt +1 ;
end
end
D(w_count) = mean((x - centers(xq)).^2);
end
end
and i call it and have these inputs :
M = 10000
t=(randn(M,1)+sqrt(-1)*randn(M,1))./sqrt(2);
A= abs(t).^2;
[xq,centers,D] = Lloyd_Max( A,2,0,4 );
I tried to comment the while and the D, Results :
I got the xq and the centers all normal, xq in the 1-4 range, centers 1-4 indexes and 0.5-3.5 range.
I dont know whats going wrong here...Please help me.
Thank in advance!
MYSTERY SOVLED!
Thank you all guys for your help!
I just putted out of the while the for loop :
for i=1:10000,
if (x(i) > max_value)
xq(i) = max_value;
elseif (x(i) < min_value)
xq(i) = min_value;
else
xq(i) = x(i);
end
end
and it worked like charm.... this loop was initilizing the array again. Sorry for that. Thank you again!
There is an assignment xq(i) = x(i) somewhere in the middle of your function, but you pass A as x from outside where you calculate A from t which is sampled by randn, so you can't promise xq is an integer.
I'm not sure exactly what you are aiming to do, but your vector xq does not contain integers, it contains doubles. If you want to use a vector of indices as you do with centers(xq), all elements of the vector need to be integers.
Upon a little inspection, it looks like xq are x values, you should find some way to map them to the integer of the closest cell to which they belong (i'm guessing 'centers' represents centers of cells?)