Vectorising equations in loop
2 views (last 30 days)
Show older comments
Konstantinos Bassamakis
on 31 Oct 2020
Edited: Ameer Hamza
on 31 Oct 2020
I have made the following code (C1) using arrays. I undertsand this is bad practise so i tried to write it again this time vectorising the equations but i keep getting "Array indices must be positive integers or logical values."
%C1: Loop with array
n=0.1;
v=[];
for i=1:n:4.9
v=[v 0.1553567*((i)^6)-2.0416*((i)^5)+9.1837*((i)^4)-14.829*((i)^3)-1.3703*((i)^2)+32.821*(i)-1.3155];
end
for i=4.9:n:15.3
v=[v 0.003980879*(i^5)-0.2247*(i^4)+4.8682*(i^3)-50.442*(i^2)+254.67*(i)-430.66];
end
for i=15.4:n:25
v=[v -0.073*(i^2)+6.1802*(i)+40.423];
end
disp(v)
t=0.9:n:25;
plot(t,v)
%C2: Loop with vectors
n=0.1;
v=[];
for i=1:n:4.9
v(i)= 0.1553567*((i)^6)-2.0416*((i)^5)+9.1837*((i)^4)-14.829*((i)^3)-1.3703*((i)^2)+32.821*(i)-1.3155;
end
for i=4.9:n:15.3
v(i)=0.003980879*(i^5)-0.2247*(i^4)+4.8682*(i^3)-50.442*(i^2)+254.67*(i)-430.66;
end
for i=15.4:n:25
v(i)= -0.073*(i^2)+6.1802*(i)+40.423;
end
disp(v)
t=0.9:n:25;
plot(t,v)
0 Comments
Accepted Answer
Ameer Hamza
on 31 Oct 2020
Edited: Ameer Hamza
on 31 Oct 2020
The main problem in your code is not using for-loop; rather, it is the dynamic growth of the v array. You need to use pre-allocation. Following shows one of the way
n=0.1;
I = 1:0.1:25;
v=zeros(size(I)); % pre-allocating the memory
for i = 1:numel(I)
if I(i) <= 4.9
v(i) = 0.1553567*((I(i))^6)-2.0416*((I(i))^5)+9.1837*((I(i))^4)-14.829*((I(i))^3)-1.3703*((I(i))^2)+32.821*(I(i))-1.3155;
elseif I(i) <= 15.3
v(i) = 0.003980879*(I(i)^5)-0.2247*(I(i)^4)+4.8682*(I(i)^3)-50.442*(I(i)^2)+254.67*(I(i))-430.66;
else
v(i) = -0.073*(I(i)^2)+6.1802*(I(i))+40.423;
end
end
disp(v)
t=1:n:25;
plot(t,v)
Or if you want loop-free vectorized version
n=0.1;
I = 1:0.1:25;
v = zeros(size(I)); % pre-allocating the memory
idx1 = I<=4.9;
v(idx1) = 0.1553567*((I(idx1)).^6)-2.0416*((I(idx1)).^5)+9.1837*((I(idx1)).^4)-14.829*((I(idx1)).^3)-1.3703*((I(idx1)).^2)+32.821*(I(idx1))-1.3155;
idx2 = (I>4.9)&(I<=15.3);
v(idx2) = 0.003980879*(I(idx2).^5)-0.2247*(I(idx2).^4)+4.8682*(I(idx2).^3)-50.442*(I(idx2).^2)+254.67*(I(idx2))-430.66;
idx3 = I>15.3;
v(idx3) = -0.073*(I(idx3).^2)+6.1802*(I(idx3))+40.423;
disp(v)
t=1:n:25;
plot(t,v)
0 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!