Why is my code giving an empty vector?
1 次查看(过去 30 天)
显示 更早的评论
The code that I have below works perfectly find when I do it in command window without using the while loop. I have to do it for a lot of time to get the answer but in the end I still get the answer. But when I run this function it gives me
out = [] and rupee = 0
why is it doing this? I have to stop when llllat =='D' and kkkkat == 0. I have the terminating command in the end but it looks like the loop doesn't end.
function [out rupee] = dat(rc, cdir, dtravel, letters, rvalues)
A = [];
B = [];
while A ~=0
row = rc(1);
erow = letters(row,:);
column = rc(2);
final = erow(column);
kat = rc(1);
kkat = dtravel(kat,:);
kkkat = rc(2);
kkkkat = kkat(column);
lat = rc(1);
llat = cdir(lat,:);
lllat = rc(2);
llllat = llat(column);
if llllat == 'D'
break;
end
pat = rc(1);
ppat = rvalues(pat,:);
pppat = rc(2);
ppppat = ppat(column);
for ind = 1:length(final)
A = [A final(ind)];
end
for ind = 1:length(ppppat)
B = [B ppppat(ind)];
end
if llllat == 'N'
w = rc(1);
b = w - kkkkat;
rc(1) = b;
elseif llllat == 'S'
w = rc(1);
b = w + kkkkat;
rc(1) = b;
elseif llllat == 'E'
w = rc(2);
b = w + kkkkat;
rc(2) = b;
else
w = rc(2);
b = w - kkkkat;
rc(2) = b;
if kkkkat == 0
break;
end
if llllat == 'D'
break;
end
end
end
out = A;
rupee = sum(B);
end
If you would like to check it I can post the test cases.
1 个评论
Stephen23
2015-2-21
@Kratos: this code could be be much improved with some array preallocation and vectorizing most of the arithmetic. Because doing this makes for much neater and compact code (as well as being faster) you will be able to have a better overview of the code and understand its operation better.
回答(1 个)
Image Analyst
2015-2-21
I don't know what your input parameters are so about all I can say is that usually when you want to compare strings you use strcmp(), strcmpi(), or strfind(), not the == operator. Try that and also try using the debugger to step through your code one line at a time to figure out why the loop never exits.
2 个评论
Image Analyst
2015-2-21
When you used the debugger, did the code execution follow different paths? Or did you not even use the debugger at all?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!