Changing the size of an array in a while loop

18 views (last 30 days)
I am trying to interpret a series of data iteratively, but am having a problem with my arrays not being the same size (Error: Matrix dimensions must agree).
The problem is, I have a series of data points that are calculated and I must then take the derivative of that data set and compare the derivative to the original data set, and do this multiple times until the difference is within a convergence factor.
For example: say I have an initial data set A_o, which is a 1000x1 matrix. I then take the derivative of A_o (which I have called A_i), which returns a 999x1 matrix. I then need to compare the difference between A_o and A_i to see if they are within a set convergence factor, and if not, re-run the calculation with A_i now taking the place of A_o and A_i+1 being the derivative of A_i. So A_i+1 will be a 998x1 matrix, and so on. I have chosen to set this up using a while loop.
Everytime I take the derivative, it makes the arrays a different size and thus the code will not run. I also have to multiply this by another data set (I have called 'I') as well. Essentially, I don't know how to systematically reduce the size of my array by 1 point each time it goes through the loop.
Any help would be greatly appreciated. I have attatched the problematic part of the code below.
% A_0 is my inital array of data, calulated and brought in from another function.
% I is another array of data with the same number of data points as A_0
dt = 0.2 % A set time interval between datapoints
A_i = (diff(A_0)/dt).*I.^2; %My equation to get to the next iteration using the derivative of A_0
conv_con = A_0 - A_i;
while conv_con > 1e-9
A_0 = A_0 + A_i;
A_i = (diff(A_0)/dt).*I.^2;
end

Accepted Answer

Sindar
Sindar on 15 Oct 2020
keeps the vector the same length
A_i = gradient(A_0,dt).*I.^2;
changes size of vector (and uses a for loop since there are a known number of possible iterations)
% A_0 is my inital array of data, calulated and brought in from another function.
% I is another array of data with the same number of data points as A_0
dt = 0.2 % A set time interval between datapoints
A_i = (diff(A_0)/dt).*I.^2; %My equation to get to the next iteration using the derivative of A_0
for ind=1:length(A_0)
% "re-run the calculation with A_i now taking the place of A_o"
A_0 = A_i;
% something else
%A_0 = A_0(1:end-1) + A_i;
A_i = (diff(A_0)/dt).*I(1:end-ind).^2;
if all((A_0 - A_i)<1e-9)
break
end
end
if ind==length(A_0) && all((A_0 - A_i)<1e-9)
warning('Not converged')
end

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!