简体   繁体   中英

octave matrix for loop performance

I am new to Octave. I have two matrices. I have to compare a particular column of a one matrix with the other(my matrix A is containing more than 5 variables, similarly matrix B is containing the same.) and if elements in column one of matrix A is equal to elements in the second matrix B then I have to use the third column of second matrix B to compute certain values.I am doing this with octave by using for loop, but it consumes a lot of time to do the computation for single day, i have to do this for a year. Because size of matrices is very large.Please suggest some alternative way so that I can reduce my time and computation. Thank you in advance.

Thanks for your quick response -hfs continuation of the same problem, Thank u, but this will work only if both elements in both the rows are equal.For example my matrices are like this,

A=[1 2 3;4 5 6;7 8 9;6 9 1]
B=[1 2 4; 4 2 6; 7 5 8;3 8 4]

here column 1 of first element of A is equal to column 1 of first element of B,even the second column hence I can take the third element of B, but for the second element of column 1 is equal in A and B,but second element of column 2 is different,here it should search for that element and print the element in the third column,and am doing this with for loop which is very slow because of larger dimension.In mine actual problem I have given for loop as written below:

for k=1:37651
    for j=1:26018
       if (s(k,1:2)==l(j,1:2))
          z=sin((90-s(k,3))*pi/180) , break ,end

      end
  end 

I want an alternative way to do this which should be faster than this.

You should work with complete matrices or vectors whenever possible. You should try commands and inspect intermediate results in the interactive shell to see how they fit together.

A(:,1)

selects the first column of a matrix. You can compare matrices/vectors and the result is a matrix/vector of 0/1 again:

> A(:,1) == B(:,1)
ans =

  1
  1
  0

If you assign the result you can use it again to index into matrices:

I = A(:,1) == B(:,1)
B(I, 3)

This selects the third column of B of those rows where the first column of A and B is equal.

I hope this gets you started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM