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
    4 ビュー (過去 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.
0 件のコメント
回答 (1 件)
  Ngoc Thanh Hung Bui
      
 2018 年 4 月 30 日
        
      編集済み: 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 件のコメント
  Ngoc Thanh Hung Bui
      
 2018 年 5 月 1 日
				
      編集済み: 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 Center および File Exchange で Loops and Conditional Statements についてさらに検索
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

