Matlab

Moderators: None (Apply to moderate this forum)
Number of threads: 1467
Number of posts: 2144

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Problem with dynamic programming Posted by KikiDi on 3 May 2011 at 12:45 AM
Hello,
I am trying to write a code that can find the maximum sum of a consecutive subsequence of an array. I am trying to do this dynamically but I am new to matlab. So far I have this code:


function [count] = weight(a)


if nargin == 0,
a = [3, 5, 1, -4, 0, 3, 2, 8, -9, 5, 2];
[count] = weight(a);
fprintf('Array A is :');
disp (a);
fprintf('Weight of the maximum consecutive subsequence is %i\n', count);
end


[c n] = size(a); %size of a
M = zeros(n);
M(1,:) = 0;


% dynamic code
for i=1:n,
M(i) = max(M(i-1)+A(i), A(i));
count = M(n);
end



But of course it doesn't work. Can anyone help please?

Thank you
Report
Re: Problem with dynamic programming Posted by sambo8 on 8 May 2011 at 8:42 PM
1- Your first mistake is that you cannot call a function in itself. So you must suppress the line [count] = weight(a) after declaring a (a = []).

2- You have an "end" missing for function, which makes it three now.
3- fprintf()for displaying count must be either suppressed or cut and pasted further below. I put it after the loop "for".
4- You must set the counter of the loop "for" to two, then the subscript i-1 set to one.
With all those changes saved, I find 13. Here's the code. I hope it helps:

function [count] = weight(a)

if nargin == 0,
a = [3, 5, 1, -4, 0, 3, 2, 8, -9, 5, 2];
fprintf('Array A is :');
disp(a);
end


[c n] = size(a); %size of a
M = zeros(n);
M(1,:) = 0;


% dynamic code
for i=2:n
M(i) = max(M(i-1)+a(i), a(i));
end
count = M(n);
fprintf('Weight of the maximum consecutive subsequence is %i\n', count);
end




 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.