I am new with Matlab, and I have the a code with two loops and I need vectorize, Can someone help me?
function f = eval_Funcion_RHE(x)
n = length(x);
f = 0;
for i = 1:n
sumaInt = 0;
for j = 1: i
sumaInt = sumaInt + (x(j)^2);
end
f = f + sumaInt;
end
end

 採用された回答

Bruno Luong
Bruno Luong 2018 年 10 月 7 日
編集済み: Bruno Luong 2018 年 10 月 7 日

1 投票

x = x(:).';
f = sum(x.^2.*(length(x):-1:1))

7 件のコメント

Iori Yagami Kusanagi
Iori Yagami Kusanagi 2018 年 10 月 7 日
Thank you so much... I will try!
Iori Yagami Kusanagi
Iori Yagami Kusanagi 2018 年 10 月 7 日
編集済み: Iori Yagami Kusanagi 2018 年 10 月 7 日
@Bruno Luong: Now, if the function is more complex, how can you optimize it?
for i = 1:n-1
a = max (i-1,1);
b = min (i+1,n);
prodc = 1;
for j = a: b
prodc = prodc * (x(j)^3);
end
f = f + prodc;
end
Bruno Luong
Bruno Luong 2018 年 10 月 7 日
編集済み: Bruno Luong 2018 年 10 月 8 日
fp = exp(3*conv(log(x(:)),ones(3,1)));
f = real(sum(fp(2:n)))
Iori Yagami Kusanagi
Iori Yagami Kusanagi 2018 年 10 月 7 日
I tried, but i get this message: Error using conv2
Error using conv2 Invalid data type. First and second arguments must be numeric or logical.
Error in conv (line 43) c = conv2(a(:),b(:),shape);
Error in Funcion_EN (line 9) fp = exp(3*conv(log(x(1:n)),ones(3,1)));
Bruno Luong
Bruno Luong 2018 年 10 月 8 日
make sure x contain numbers, make sure you don't name something else ONES.
Put a breakpoint and check.
Bruno Luong
Bruno Luong 2018 年 10 月 8 日
編集済み: Bruno Luong 2018 年 10 月 8 日
I run this:
% random input
x= rand(1,10);
% for-loop method
n = length(x);
f = 0;
for i = 1:n-1
a = max (i-1,1);
b = min (i+1,n);
prodc = 1;
for j = a: b
prodc = prodc * (x(j)^3);
end
f = f + prodc;
end
f
% vectorize method with conv
n = length(x);
fp = exp(3*conv(log(x(:)),ones(3,1)));
f = real(sum(fp(2:n)))
I get this
>> test
f =
0.0199
f =
0.0199
>>
Iori Yagami Kusanagi
Iori Yagami Kusanagi 2018 年 10 月 8 日
Thank you, again!!!

サインインしてコメントする。

その他の回答 (0 件)

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by