Iterating over a vector to create a cell array without for loop

I would like to know if it is possible to do the same as the code below without a for loop:
for i=1:length(index)
date1{i}=datenum(datos.Date(index(i):end));
Y{i}=(datos.High(index(i):end)+datos.Low(index(i):end))./2;
X{i}=[ones(length(Y{i}),1) date1{i}];
b{i}=regress(Y{i},X{i});
tendency{i}=b{i}(1)+b{i}(2)*X{i}(:,2);
parallel{i}=std(Y{i});
end

 Akzeptierte Antwort

Jan
Jan am 21 Dez. 2020
Most likely this cannot be vectorized. By why do you ask for it? Do you want to accelerate the code? This is possible:
Avoid repeated work. E.g.
date1{i}=datenum(datos.Date(index(i):end));
Convetry many date repeatedly. So move this befor the loop to convert the dates once only:
date1V = datenum(datos.Date);
% and inside the loop:
date1{i} = date1V(index(i):end);
regress() is a very powerful function. All you want to do is a polynomial fit. Then this is probably faster:
function p = TinyPolyFit(x, y, n)
% Construct Vandermonde matrix:
x = x(:);
V = ones(length(x), n + 1);
for j = n:-1:1
V(:, j) = V(:, j + 1) .* x;
end
% Solve least squares problem:
[Q, R] = qr(V, 0);
p = transpose(R \ (transpose(Q) * y(:)));
end

1 Kommentar

Thank you so much. I did want to accelerate the code and it worked perfectly.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu MATLAB finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by