MATLAB: Insert a vector into a matrix without where the row placement is given from a number

matrixmatrix arraymatrix manipulationvector

Hi
I have this starting matrix that shows different layers into the soil.
A_example_1 = [0 -0.1; -0.1 -4.7; -4.7 -5];
I need a code that decides where to add my vector into my matrix. Ive defined that:
% Add layer in given depth for both example 1 and 2. In this code the example 1 i chosen.
vector_add = A_example_1(end,2)+1.15;
Now if the matrix is as A is right now, the program should add a layer so it gives this matrix:
ans_example_1 = [0 -0.1; -0.1 -3.85; -3.85 -4.7; -4.7 -5];
However… If the A matrix starts by having these layers:
A_example_2 = [0 -0.1; -0.1 -3; -3 -5];
Then the code should create a matrix that looks like this:
ans_example_2 = [0 -0.1; -0.1 -3; -3 -3.85; -3.85 -5]

Best Answer

yeah, the vector_add formulation is odd, and the direction is worng (?), but i think i see what you mean. you actually just have a list of boundary points for the layers - why not add the new boundary point to a vector of these points, then run a couple of lines to sort these and then create the matrix?
% use vector list of layer boundary positions
oldBoundList = [0 -0.1 -4.7 -5];
newBound = oldBoundList(3) + 1.15; % or just 'newBound = -3.55;' etc
newBoundList = sort(horzcat(oldBoundList, newBound), 'descend');
% write matrix
nLayers = length(newBoundList)-1;
mat = NaN(nLayers,2);
for i = 1:nLayers
mat(i,:) = [newBoundList(i) newBoundList(i+1)];
end
this should give you what you want.