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 次查看(过去 30 天)
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.

回答(1 个)

Ngoc Thanh Hung Bui
编辑:Ngoc Thanh Hung Bui 2018-4-30
%% 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 个评论
rayray
rayray 2018-4-30
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 2018-5-1
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by