While loop in Octave taking too long


I have written a small code in Octave and part of it is checking whether values in the first rows of two matrices are equal, and if so, adding the value of the second row of the second matrix to the value of the second row of the first matrix.

This is that part of the code that I have written:

x=1; #row number in matrix X
y=1; #row number in matrix PositionLoadArray

while y<=columns(PositionLoadArray)

   if PositionLoadArray(1,y)==X(1,x) 


The loop runs and works perfectly for small sets (i.e. where the total number of columns for X and PositionLoadArray (max. values of x and y, respectively) are small). But the loop takes too long to be executed with larger values.

How can I reduce the execution time and get the same result?


I am not sure if I understood well the purpose of your code because you didn't give an example for the values taken by PositionLoadArray. However, if you want to compare two matrices and add rows depending on the boolean result, you can inspire yourself from the comparison operators on matrices (http://www.gnu.org/software/octave/doc/v4.0.1/Comparison-Ops.html). An example :

A = [ 1 2 ; 3 4 ]
B = [ 2 2 ; 3 3 ]
mat = A == B  // indexes where A = B
A(mat) = 5    // where A==B, replace the values of A by 5

PS Octave is not a programming language taught in Codecademy, you should not post this question on this website :slight_smile: