Home > front end >  How to loop over 3 elements of an array?
How to loop over 3 elements of an array?

Time:01-04

I am trying to create a loop that selects 3 rows from an array at a time and does some calculation later.

For example:

array = [2 3 4; 4 5 6; 7 8 9; 10 11 23; 23 56 78; 67 55 89; 90 87 32]

So in the first loop it should select [2 3 4; 4 5 6; 7 8 9]

and in the second loop [10 11 23; 23 56 78; 67 55 89].

I am struggling to make this possible.

CodePudding user response:

Hope the code Help:

clear, clc
% Array 
Arr = [2 3 4; 4 5 6; 7 8 9; 10 11 23; 23 56 78; 67 55 89; 90 87 32];
% Define The Length to Prevent the Error of Iteration in For Loop
if mod(size(Arr,1),3) ==0
    LenArr = size(Arr,1); % Length Examined 
else
    LenArr = size(Arr,1) - mod(size(Arr,1),3);
end
Counter = 1;  
for i = 1:3: LenArr
    Iter = Arr(i:i 2, :); % Here the Answer of the Question 
    % Disply Results ----------
    fprintf('Iteration %d = \n',Counter)  
    disp(Iter)
    Counter = Counter 1;
    %--------------------------
end

Results:

Iteration 1 = 
     2     3     4
     4     5     6
     7     8     9

Iteration 2 = 
    10    11    23
    23    56    78
    67    55    89

CodePudding user response:

you can do this like below code

your algorithms can be applied to selectBlockLocations variable.

array = [2 3 4; 4 5 6; 7 8 9; 10 11 23; 23 56 78; 67 55 89; 90 87 32];

number_of_loop = floor(length(array)/3);

for i=0:number_of_loop-1
    selectBlockLocations = array(i*3 1:i*3 3, 1:end);
    disp(selectBlockLocations)
end

result:

 2     3     4
 4     5     6
 7     8     9

10    11    23
23    56    78
67    55    89

Have a good time!

  • Related