MATLAB Answers

how to write this c++ code in matlab form

4 ビュー (過去 30 日間)
Arvind Sharma
Arvind Sharma 2018 年 9 月 11 日
編集済み: Walter Roberson 2018 年 9 月 12 日
for(i=0;i<=80;i++) {
wv[i]=380+i*5;
}
double findpeak( double* wv, double x[][50]) // find the peak of a spectrum
{ double temp=x[0][0];
int index=0;
for(int i=1;i<=80;i++)
{ if (x[i][0]>temp)
{ temp=x[i][0];index=i;};
}
return wv[index];
};

  2 件のコメント

Walter Roberson
Walter Roberson 2018 年 9 月 11 日
That is not valid c++ code. You allocate x as a 2d array with 0 rows and 0 columns and no particular initial value. This local variable hides the x passed in as an parameter. You then attempt to access the second through eighty first columns of the empty x and you expect that array overrun to work and to have initialized values.
Stephen Cobeldick
Stephen Cobeldick 2018 年 9 月 11 日
for(i=0;i<=80;i++) { wv[i]=380+i*5; } double findpeak( double* wv, double x[][50]) // find the peak of a spectrum { double temp=x[0][0]; int index=0; for(int i=1;i<=80;i++) { if (x[i][0]>temp) {temp=x[i][0];index=i;}; } return wv[index]; };

サインイン to comment.

回答 (2 件)

Walter Roberson
Walter Roberson 2018 年 9 月 11 日
The equivalent MATLAB code would be
error('Subscript out of range') ;

  2 件のコメント

John D'Errico
John D'Errico 2018 年 9 月 12 日
:)
James Tursa
James Tursa 2018 年 9 月 12 日
Or
exit

サインイン to comment.


Guillaume
Guillaume 2018 年 9 月 11 日
is it correct
Certainly not! It doesn't look like you know what the zeros function does.
x = zeros(0,0);
is exactly the same as
x = [];
and creates an empty matrix. zeros(j, 0) creates a matrix with j rows and 0 columns, another kind of empty matrix. Why would you want to compare that to another empty matrix?
how to write this c++ code in matlab form
Matlab is not C++ and trying to translate C++ code into matlab line by line would be a complete waste of time. C++ is a low level language where you have to write all the operations yourself. In matlab, you can use higher level function that do the work for you. Case in point, that C++ findpeak function would be just two lines in matlab:
function peak = findpeak(wv, x)
[~, idx] = max(x(:, 1));
peak = wv(idx);
end

  0 件のコメント

サインイン to comment.

サインイン してこの質問に回答します。

タグ

製品


Translated by