Concatenate arrays in foor loop. Torque problem
Show older comments
Torque problem
I'm trying to concatenate arrays in foor loop ta one Array containing all values.
The last value in Array Mloc are the same value as the first value in Mloc in the next loop so the first value in every loop should not be omitted (or the last)
say I have these
d= [0 0 0 0 0 0 0 0 0 0]
a = [0 5 8 7] b = [7 5 3 4] c = [4 5 2 6]
The result I want:
d = [0 5 8 7 5 3 4 5 2 6]
My code so far:
npl=1000; % x-Pos on beam where torque should be calculated
n=4; % number of fields
L=[3 6 2 5] % length of each field
j=0;
k=0;
Mbeam=zeros(n*(npl-1)+1,1); % preallocate memory for Array with torque values over entire beam
for i=1:n % loops over every field
j=k; % lower x-value on current field
k=j+L(i); % higher x-value on current field
x=linspace(j,k,npl)'; % creats npl x Points in current field
Mloc=MA(i) + RA(i).*x + (q(i).*(x.^2))./2; % Calculates an Array with the torque value in every x for ONE field
Mbeam=[Mbeam;Mloc];
% Here is the problem. As above i want to concatenate Mloc with Mbeam
without placing Mloc after all the zeros in Mbeam.
As discribed above I would also like to see to that the first value in Mloc during the second loop
overwrites the current last value in Mbeam making the total length of the final Mbeam = 3997
end
Most grateful for help.
1 Comment
Stephen23
on 19 Jan 2017
You need to index into Mbeam, not keep on expanding it using concatenation.
Accepted Answer
More Answers (1)
If I understood correctly, this would achieve what you want a lot simpler:
L = [3 6 2 5];
npl = 1000;
%I'm assuming that MA, RA and q are all ROW vectors with the same number of elements as L
cuml = cumsum(L);
x = cell2mat(arrayfun(@(s, e) linspace(s, e, npl)', [0 cuml(1:end-1)], cuml, 'UniformOutput', false));
Mloc = MA + RA.*x + q.*(x.^2)/2; %<---- This assumes R2016b
Mbeam = [reshape(Mloc(1:end-1, :), [], 1); Mloc(end)];
If using a version earlier than R2016b, replace the marked line by
Mloc = bsxfun(@plus, MA, bsxfun(@times, RA, x) + bsxfun(@times, q, x.^2)/2);
Basically, create all your x coordinates in one go as a npl x 4 matrix. Calculate your Mloc in one go using that matrix, and reshape into a single column ignoring the last row.
Categories
Find more on Descriptive Statistics and Visualization 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!