登录论坛

查看完整版本 : [求助]一个简单算法的实现??


sallap
2008-11-07, 09:00
一个数组,如:A=(0 0 0 0 0 3.5 4.7 0 0 0 8 0 9.0 4.5 6.5 9)
要求:
求出A中所有连续不为0的片段中,每一个数据和片段最大值的乘积,然后求该数组中上述乘积之和。
比如上式,应该求出如下值:
(3.5+4.7)*max(3.5,4.7) +8*8+(9.0+4.5+6.5+9)*max(9.0, 4.5, 6.5,9)

这个算法该如何实现? 可能很简单,但我在写条件语句while或if时,总跳入死循环。
请教高手。多谢。

meatball1982
2008-11-07, 23:19
clear all
clc
A=[0 0 0 0 0 3.5 4.7 0 0 0 8 0 9.0 4.5 6.5 9];
n=length(A);
A=[A,0];
k=1;
if A(1)==0;
temp=[];
else
temp=A(1);
end
for i=1:n
if A(i)~=0
temp=[temp,A(i)];
if A(i+1)==0
temp_out(k)=sum(temp)*max(temp);
temp=[];
k=k+1;
end
end
end
out=sum(temp_out)
(3.5+4.7)*max([3.5,4.7])+8*8+(9.0+4.5+6.5+9)*max([9.0, 4.5, 6.5,9])

meatball1982
2008-11-07, 23:20
有点笨,希望有帮助吧。