Problem with dynamic programming

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:


[b]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
', 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[/b]


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

Thank you

Comments

  • 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
    ', count);
    end

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion