Tried to ask this at Matlab Central, and didn't get much replies.
This is the code:
for
... creates "cent"
end
e = 5 ;
per = zeros(e,e)
for u = 1:e
rsum = 0;
a = 0;
for p=1:e
u
p
Xdiff = 0;
Ydiff = 0;
Zdiff = 0;
Xdiff = (cent(u,1)-cent(:,1)).^2
Ydiff = (cent(u,2)-cent(:,2)).^2
Zdiff = (cent(u,3)-cent(:,3)).^2
a = (Xdiff + Ydiff + Zdiff).^0.5
rsum = cent(u,6) + cent(:,6) ;
if a == rsum(p)
per(p,u) = p ;
else
per(p,u) = 0 ;
end
end
end
The script runs just fine, and I get no error messages. However, i get no display of u and p, and per is returned as a matrix with only zeros if i create it before the first for loop. If i create per as shown over, between the first and second, it is not created at all. I thus think that the code stops after the first loop. Why?
Related
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!
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
I am trying to read some magnetic fields using Matlab. To do so, I am using Windows XP OS and I am sending the command to continuos reading from the device using Putty. While Putty its running and saving the log file I am reading this log file on Matlab. The Device is a HMR2300.
When I am reading this using ASCII format I am not facing any problems at all. However, I need to collect this data in binary and this is the problem.
The output string is 7 bytes long "Xh|Xl|Yh|Yl|Zh|Zl|" Xh = Signed Byte, X axis - Xl= Low byte, X axis.
Since I have four devices, I am collecting all data inside of a while loop with this code:
%*****% Reading from Device 01
[D1, N] = fread(FidMag1, 7);
while (true)
MagData1 = [MagData1, D1'];
CRLF1 = find(MagData1 == 13);
CRLF1 = [0, CRLF1]';
if (CRLF1(end) ~= 7)
MagData1(1:CRLF1(end))=[];
[D1, N] = fread(FidMag1, 7);
else
break;
end
end
ttt = clock();
TimeStamp1(Count) = ttt(6) + ttt(5)*60 + ttt(4)*3600;
NoCalMagX1(Count) = int16(typecast(uint8(MagData1(1)), 'int8')) * int16(256) + (MagData1(2));
NoCalMagY1(Count) = int16(typecast(uint8(MagData1(3)), 'int8')) * int16(256) + (MagData1(4));
NoCalMagZ1(Count) = int16(typecast(uint8(MagData1(5)), 'int8')) * int16(256) + (MagData1(6));
MagData1(1:CRLF1(end))=[];
So, after that I am reading in a row devices 2, 3, and 4.
This is my result:
Image Link
You can see roughly that before and after 200 sec I am having a delay to collect the data and this is what I need to solve. Usually when my field starts to change, I start to receive a delay and I don't know how to solve it.
I've tried to do a different approach with my code however this is just worst then the first one:
%*****% Reading from Device 01
if (SYNC_1)
[D1, countB] = fread(FidMag1, 7-BIB_1);
if (countB ~= 7)
for a=1:countB
temp(BIB_1+a) = D1(a);
end
end
if (flag_temp)
flag_temp = 0;
else if(find(D1 == 13) == 7)
for a=1:countB
temp(a) = D1(a);
end
end
end
BIB_1 = BIB_1 + countB;
if(BIB_1 == 7)
if (find(temp == 13) == 7)
ttt = clock();
TimeStamp1(Count_1) = ttt(6) + ttt(5)*60 + ttt(4)*3600;
NoCalMagX1(Count_1) = int16(typecast(uint8(temp(1)), 'int8')) * int16(256) + (temp(2));
NoCalMagY1(Count_1) = int16(typecast(uint8(temp(3)), 'int8')) * int16(256) + (temp(4));
NoCalMagZ1(Count_1) = int16(typecast(uint8(temp(5)), 'int8')) * int16(256) + (temp(6));
fprintf('SENSOR B\nX:%.0f Y:%.0f Z:%.0f\n\n', NoCalMagX1(Count_1), NoCalMagY1(Count_1), NoCalMagZ1(Count_1));
Count_1 = Count_1 + 1;
else
SYNC_1 = 0;
end
BIB_1 = 0;
end
end
if (~SYNC_1)
[D1, countB] = fread(FidMag1, 7-BIB_1);
BIB_1 = BIB_1 + countB;
if (BIB_1 > 0)
index = find (D1 == 13);
if(index)
BIB_1 = 7 - index(end);
if(BIB_1 == 0)
flag_temp = 1;
for a=(BIB_1+1):7
temp(a-BIB_1) = D1(a);
end
else
for a=(index+1):countB
temp(aux) = D1(a);
aux = aux + 1;
end
end
aux = 1; %temp index
SYNC_1 = 1;
else
SYNC_1 = 0;
BIB_1 = 0;
end
end
end
Results:
Image Link
Do you guys have any idea how can I solve this? To collect data using ascii my approach its similar and I don't have any problems. Also when I am reading from just one device using the first code I don't have any problems too. I am just lost in how to solve that.
largest = 0;
num = 0;
temp = 0;
num_flip = 0;
for x = 100 : 999
for y = x : 999
num = x*y;
temp = num2str(num);
num_flip = str2double(fliplr(temp));
if num/num_flip == 1
largest = num;
one = x;
two = y;
end
end
end
I'm trying to find the largest palindrome made from the product of two 3-digit numbers but for some reason my the loop stops at x = 924 and y = 962 but I know that's not answer. The code works fine for 2-digit numbers(10 : 99) though.
You are not testing if largest is truly the largest with that code. As you go through the loops it is possible that a smaller palindrome will be detected after a larger one, and you are reassigning largest to it.
Try this with an added test for whether a new palindrome is larger than the current largest:
largest = 0;
num = 0;
temp = 0;
num_flip = 0;
for x = 100 : 999
for y = x : 999
num = x*y;
temp = num2str(num);
num_flip = str2double(fliplr(temp));
if ((num/num_flip) == 1) && (num > largest)
largest = num;
end
end
end
I removed these assignments
one = x;
two = y;
because it's not clear what they are for from your question. Add them back if they are needed for a reason not shown.
Posting the entirety of my code in the hope somebody can help me debug this crap. Really hoping to reach a conclusion soon because I've been toying with this for way too long.
I have here a function extract which is passed a grid of integers which represent letters (i.e A=1,Z=26) from my wordsearch function. Given a direction and a target word which is represented by a row vector of ints, it should iterate through the grid to find where the first letter exists and move in all directions from here for length of the word and extract the word e.g. if we are looking for [14, 5, 9, 2] and 14 is first positioned at (4,4) we should end up at (4,8).
The word is then compared in the search function and if it matches the target word, a line is drawn from first letter to the last on an image of the actual wordsearch.
I know my if and for loops are off in some places but I'm finding it difficult to correct my code so that it works. Help! One thing in particular I'm having difficulty with is controlling flow so that if after checking all directions from a square containing the first letter, the next instance of that letter is evaluated. Where would it be best to do this?
Code has lots of errors as it is and could do with a couple of pointers telling me where it needs altering or cleaning up.
%//A function to find a word in a grid.
function test = extract(grid, direction, target)
%//switch through different cases that allow us to move to any adjacent cell to the current
switch upper(direction)
case 1
rowdir = -1;
coldir = 0;
case 2
rowdir = -1;
coldir = 1;
case 3
rowdir = 0;
coldir = 1;
case 4
rowdir = 1;
coldir = 1;
case 5
rowdir = 1;
coldir = 0;
case 6
rowdir = 1;
coldir = -1;
case 7
rowdir = 0;
coldir = -1;
case 8
rowdir = -1;
coldir = -1;
end
[i, j] = size(grid);
len = length(target);
[row,column] = find(target(1)==grid); %//find the letter of the word we are looking for in grid
%//row and column of last letter having moved in a particular direction
rowN = row + (len-1) * rowdir;
colN = column + (len-1) * coldir;
%//trying to say here to only move in a particular direction if we don't go out of bounds.
%//not sure I've succeeded
if (rowN > 1) | (rowN < i) | (colN > 1) | (colN < j)
testword = []; %empty array created
for index = 1:len
index_1 = index-1;
%//on loop get the letter in adjacent cell for direction we have moved
word = grid(row + (index_1 * rowdir), column + (index_1 * coldir));
testword{index} = word; %//letters are appended to create word for which we compare.
%//get co-ords of start letter. change to pixel co-ordinates so we can evaluate on image
wordstart = [(row*30)-15, (column*30)-15 ];
wordend = [((row + (len-1 * rowdir))*30)-15, ((column + (len-1 * coldir))*30)-15];
end
else
word = '';
end
x1 = wordstart(1);
x2 = wordend(1);
y1 = wordstart(2);
y2 = wordend(2);
test = [ word , [x1,x2] , [y1,y2]]; %//only way I could think of to get all of these as outputs
end
%//test is the image we want to evaluate on
%//words is the list of words
function trial1 = wordsearch(test, words)
imagesc(test);
colormap(gray);
hold on;
grid = %//grid is a 15x15 matrix
[row, column] = size(grid);
for iword = 1 : length(words)
target = char(words(iword)) - 'a' + 1;
for i = 1:row
for j = 1:column
for direction_num = 1:8 %//for each direction
direction = directions(direction_num, :);
testword = extract(grid,direction,target);
if testword(1)==target %//if word we have extracted equals the target word
%//draw_line function takes x co-ordinates and y co-ordinates and plots line.
draw_line(testword(2),testword(3),testword(4),testword(5));
end
end
end
end
end
hold off;
end
#Dan
My extract function now looks like:
[i, j] = size(grid);
len = length(target);
[row,column] = find(target(1)==grid);
for ii = 1:length(row)
start_row = row(ii);
start_column = column(ii);
rowN = start_row + len-1 * rowdir;
colN = start_column + len-1 * coldir;
if (rowN > 1) || (rowN < i) || (colN > 1) || (colN < j)
testword = [];
for index = 1:len
index_1 = index-1;
word = grid(start_row + (index_1 * rowdir), start_column + (index_1 * coldir));
testword{index} = word;
wordstart = [(start_row*30)-15, (start_column*30)-15 ];
wordend = [((start_row + (len-1 * rowdir))*30)-15, ((start_column + (len-1 * coldir))*30)-15];
end
else
end
end
What would I put as an else statement to check the word if previous in that particular direction takes you out of bounds?
for iword = 1 : length(words)
target = char(words(iword)) - 'a' + 1;
for i = 1:row
for j = 1:column
for direction_num = 1:8 %//for each direction
For every word, you are looping through every element in the grid (i.e. the i and j loops) but you don't actually ever use these i or j values. So those two loops do nothing! This is because you seems to do all of that inside your extract function. So drop those two loops, they are wasting an inordinate amount of time.
Inside your extract function, you have a line [row,column] = find.... This will find ALL the possible starting points. So you actually need to loop through either of those somewhere. So instead of your if (rowN > 1) | (rowN < i) | (colN > 1) | (colN < j) I would suggest something more like:
for ii = 1:length(row)
start_row = row(ii);
start_column = column(ii);
%// And now re-use your code, but swap out all your row for start_row and your column for start_column
.
.
.
end
That is the loop that will go through each of the possible starting letters.