Filter löschen
Filter löschen

how to switch from C language to matlab?

1 Ansicht (letzte 30 Tage)
AURORA SCALINCI
AURORA SCALINCI am 17 Mai 2022
Beantwortet: Pratik Pawar am 20 Mai 2022
i should rewrite this code in C on matlab
#include<stdio.h>
int main()
{
int i,j,k,n;
float A[20][20],c,x[10],sum=0.0;
printf("\nEnter the order of matrix: ");
scanf("%d",&n);
printf("\nEnter the elements of augmented matrix row-wise:\n\n");
for(i=1; i<=n; i++)
{
for(j=1; j<=(n+1); j++)
{
printf("A[%d][%d] : ", i,j);
scanf("%f",&A[i][j]);
}
}
for(j=1; j<=n; j++) /* loop for the generation of upper triangular matrix*/
{
for(i=1; i<=n; i++)
{
if(i>j)
{
c=A[i][j]/A[j][j];
for(k=1; k<=n+1; k++)
{
A[i][k]=A[i][k]-c*A[j][k];
}
}
}
}
x[n]=A[n][n+1]/A[n][n];
/* this loop is for backward substitution*/
for(i=n-1; i>=1; i--)
{
sum=0;
for(j=i+1; j<=n; j++)
{
sum=sum+A[i][j]*x[j];
}
x[i]=(A[i][n+1]-sum)/A[i][i];
}
printf("\nThe solution is: \n");
for(i=1; i<=n; i++)
{
printf("\nx%d=%f\t",i,x[i]); /* x1, x2, x3 are the required solutions*/
}
return(0);
}

Antworten (1)

Pratik Pawar
Pratik Pawar am 20 Mai 2022
This code is performing Gaussian Elimination.
Please refer to the C code converted to MATLAB below:
% script_name.m
% input augmented matrix
n = input('Enter the order of matrix: ');
disp(' ');
A = zeros(n, n+1);
for i=1:n
for j=1:n+1
A(i,j)=input(sprintf('Input the matrix value for (%d,%d): ', i, j));
end
end
% separate last column of augmented matrix as b and define x
b = A(1:n, n+1);
% forward elimination code to convert matrix A to upper triangular matrix
for j = 1:n-1
for i = n:-1:j+1
m = A(i,j)/A(j,j);
A(i,:) = A(i,:) - m*A(j,:);
b(i) = b(i) - m*b(j);
end
end
% back substitution to find x
x = zeros(n,1);
x(n) = b(n)/A(n,n);
for i = n-1:-1:1
sum = 0;
for j = n:-1:i+1
sum = sum + A(i,j)*x(j);
end
x(i) = (b(i)- sum)/A(i,i);
end
% display roots
x
MATLAB allows processing all the values in a matrix using single arithmatic operator. So, a doble 'for loop' can be avoided to improve time complexity.
% preferred
% script_name.m
% input augmented matrix
n = input('Enter the order of matrix: ');
disp(' ');
A = zeros(n, n+1);
for i=1:n
for j=1:n+1
A(i,j)=input(sprintf('Input the matrix value for (%d,%d): ', i, j));
end
end
% separate last column of augmented matrix as b and define x
b = A(1:n, n+1);
x = zeros(n, 1);
% forward elimination code to convert matrix A to upper triangular matrix
for i=1:n-1
m = A(i+1:n, i) / A(i, i);
A(i+1:n, :) = A(i+1:n, :) - m*A(i, :);
b(i+1:n, :) = b(i+1:n, :) - m*b(i, :);
end
% back substitution to find x
x(n, :) = b(n, :) / A(n, n);
for i=n-1:-1:1
x(i, :) = (b(i, :) - A(i, i+1:n)*x(i+1:n, :))/A(i, i);
end
% display roots
x

Kategorien

Mehr zu MATLAB finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by