How to write this C program in MATLAB?
显示 更早的评论
#include<conio.h>
#include<stdio.h>
void main()
{
int i,j,k,l,m,r;
int a[10][10];
int n=4;
clrscr();
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
a[i][j]=1;
}
}
for(i=1;i<=n;i++)
{
m=i;k=i;
for(j=1;j<=i;j++)
{
printf("[%d][%d]\t",m,j);
m--;
}
printf("\n");
}
if(k==n)
{
int p=2;
for(i=n;i>=1;i--)
{
r=k;
for(j=p;j<=n;j++)
{
printf("[%d][%d]\t",r,j);
r--;
}
printf("\n");
p++;
}
}
getch();
}
2 个评论
Walter Roberson
2013-9-21
What is the best way to define "best" ?
dpb
2013-9-21
cntrOne=0;
cntrTwo=0;
while(cntrOne<=255)
{
i=cntrOne;
while(j<cntrOne)
...
j is undefined here...
采纳的回答
更多回答(1 个)
Jan
2013-9-21
0 个投票
- cntrTwo does not proceed, such that you get an infinite loop.
- j=0 and j++ appear inside the same block, while while(j<cntrOne) is one level higher (see dpb's comment).
- if(cntrOne==255) is an exception which occurs in the last iteration only. So better move it behind the outer loop.
My conclusion: The "best" way to convert this pseudo code to Matlab is to fix the problems at first. There is not "best" translation for buggy code.
3 个评论
Walter Roberson
2013-9-22
Maybe the "best" would be code that just calls the error routine immediately.
Febin Benjamin
2013-9-22
I'd suggest rather than posting C-like code expecting someone to read it to decipher intent ask 'how do I compute Whatever?" it is that is the objective end result.
Writing effective Matlab code utilizing the features that make Matlab what it is (namely vectorization thereby avoiding looping constructs in large part and using the builtin functionality to do the work if possible) is not much like writing procedural code in other non-vectorized languages such as Fortran and C, etc., ... at all.
So, what is the end result of the above function intended to be in words and perhaps w/ a small sample input/output? Often such code is reducible in Matlab to just a line or two instead.
For example
int a[10][10];
int n=4;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
a[i][j]=1;
}
}
The above loop (ignoring the fact that C indexing is zero-based so there the indices of a are 0-9 in each dimension even though your pseudo code uses one-based I'll presume that is an attempt to match Matlab) equates in Matlab to
n=4;
a=zeros(10);
a(1:n,1:n)=ones(n);
I've not tried to parse the remainder but undoubtedly it can also be written more succinctly as well.
And, of course, in fact there's no need for a being 10x10 as it seems that only the nxn submatrix is used and the definition is simply there to have static allocation. In Matlab with its dynamic memory management you would in reality just write
n=4;
a=ones(n);
and a "just appears" automagically. If you subsequently change n and rerun, a will be resized to fit.
类别
在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!