Clear Filters
Clear Filters

Using loops, how do I combine 2 arrays of possibly different orientations (1 could be vertical and 1 horizontal) into 1 array WITHOUT using any of MATLAB's built in concatenation functions like horzcat, etc

1 view (last 30 days)
This is some extra practice to prepare for my exam. They want us to use loops and I cannot figure out how to do it. So finalArr is the combined array of consisting of first arr1 and then followed by arr2.
for example arr1 = [4;5;6;7;24;5] and arr2 = [1,3,2]
so I guess finalArr = [4,5,6,7,24,5,1,3,2]
The way I did it without using loops:
function [finalArr] = concatArr(arr1, arr2)
[r1,c1] = size(arr1)
lenArr1 = max(r1,c1)
[r2,c2] = size(arr2)
lenArr2 = max(r2,c2)
total = lenArr1+lenArr2
start = lenArr1+1
finalArr = zeros(1, total)
finalArr(1:c1) = arr1
finalArr(start:total) = arr2
end
But I do not understand how to use loops to do this...
What I have so far using a for loop(I know it is not right):
function [arr12] = concatArr(arr1, arr2)
[r1,c1] = size(arr1)
lenArr1 = max(r1,c1)
[r2,c2] = size(arr2)
lenArr2 = max(r2,c2)
total = lenArr1+lenArr2
start = lenArr1+1
arr12 = zeros(1,total)
for i = 1:r1
for j = 1:c1
arr12(i,j) = arr1(i,j)
end
end
Any help is much appreciated. I can tell I am missing some fundamental concepts but I need some guidance thanks.

Answers (1)

Ngoc Thanh Hung Bui
Ngoc Thanh Hung Bui on 30 Apr 2018
Edited: Ngoc Thanh Hung Bui on 30 Apr 2018
%% Simple answer
arr1 = [4;5;6;7;24;5];
arr2 = [1,3,2];
finalArr = [arr1', arr2]
%% Using loop:
finalArr = zeros(1, length(arr1) + length(arr2));
for i = 1:length(arr1)
finalArr(i) = arr1(i);
end
for i = length(arr1):(length(arr1) + length(arr2))
finalArr(i) = arr2(i-length(arr1));
end
  2 Comments
rayray
rayray on 30 Apr 2018
But you don't necessarily know the orientations of the 2 input arrays. I just provided an example but it can be that you have 2 horizontally oriented arrays or 2 vertical arrays or a mixture of both
Ngoc Thanh Hung Bui
Ngoc Thanh Hung Bui on 1 May 2018
Edited: Ngoc Thanh Hung Bui on 1 May 2018
the answer using for loop is not related to the orientations of 2 input, it works for any case you mentioned, did you try it?
for the simple answer you should identify the orientations first, for examlple:
if size(arr1,1)>1 then it is vertical
if size(arr1,2)>1 then it is horizontal

Sign in to comment.

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!