soso101
soso101

Reputation: 71

convert a Matlab code into C code

I'm trying to understand and learn the C language, and since I used to work in Matlab, I'm interested in knowing how this code would be converted into C.

for j=1:n
  v=A(:,j);

  for i=1:j-1
    R(i,j)=Q(:,i)'*A(:,j);
    v=v-R(i,j)*Q(:,i);
  end

  R(j,j)=norm(v);
  Q(:,j)=v/R(j,j);
end

Upvotes: 0

Views: 775

Answers (2)

Matt
Matt

Reputation: 2846

Arrays are declared and accessed like so:

const int N = 10;   // needs to be a constant
double v[N];        // 1-d
double A[N][N];     // 2-d
v[0] = A[1][2];     // indexing starts at 0, not 1

C doesn't do automatic vectorization like matlab, so you have to do it in for-loops manually. Instead of R(i,j)=Q(:,i)'*A(:,j),

for (int k = 0; k < N; ++k) {
    R[i][j] += Q[k][i] * A[k][j];
}

That last piece also demonstrates what a for-loop looks like - the first "argument" of the "for" is the initialization of the indexing variable k, the second sets the condition under which the for loop continues, and the third increments k. The code to be executed in the loop is enclosed in braces {}.

The main logical difference is that you have to do everything element-by-element in C.

Upvotes: 2

prototoast
prototoast

Reputation: 598

Do you know about the Matlab Coder? Matlab can automatically generate c/c++ code for you. It has its limitations, but if are trying to learn c from Matlab, using the coder should be the best way for you to populate many examples.

Upvotes: 3

Related Questions