Help Converting C++ to MATLAB.
3 次查看(过去 30 天)
显示 更早的评论
How do I convert this code into MATLAB?
#include <iostream>
#include <fstream>
using namespace std;
// prototypes
float myMax(float [], float);
float myAvg(float [], float);
int main()
{
int cols = 8;
int rows = 3;
float myArray[rows][cols];
float tempArray[cols], dayMax[rows];
int r1 = 0;
float dayMaxAvg;
while(r1 < rows){
for(int c = 0; c < cols; c++){
cout << "Please enter the value for day " << r1+1 << " Truck " <<
c+1 << endl;
cin >> myArray[r1][c];
}
r1++;
}
for(int r2 = 0; r2 < rows; r2++){
for(int c =0; c < cols; c++){
tempArray[c] = myArray[r2][c];
}
dayMax[r2] = myMax(tempArray, cols);
cout << dayMax[r2] << endl;
}
dayMaxAvg = myAvg(dayMax, rows);
cout << "\n" << dayMaxAvg << endl;
cout << "The program is finished. Thanks for using our program\n";
return 0;
}// end of main
// function finds the maximum value in an array
float myMax(float theArray[], float count){
float maxValue = 0, tempMax;
for(int n = 0; n < count; n++){
if(theArray[n] > maxValue){
maxValue = theArray[n];
}
}
return maxValue;
}
// function finds the average value in an array
float myAvg(float theArray[], float count){
float avgValue, sumOfValues = 0;
for(int n = 0; n < count; n++){
sumOfValues = sumOfValues + theArray[n];
}
avgValue = sumOfValues/count;
return avgValue;
}
1 个评论
darova
2019-4-15
Do you have any specific questions? You can use mean() or max()
For user input matrix:
cols = 8;
rows = 3;
for i = 1:rows
for j = 1:cols
s = sprintf('Input x(%i,%i) value:',i,j);
x(i,j) = input('S')
end
end
回答(1 个)
James Tursa
2019-4-15
Probably easiest is just to do it by hand one line at a time. Replace the control syntax with its MATLAB counterpart, and add 1 to the indexing. E.g., this
// function finds the average value in an array
float myAvg(float theArray[], float count){
float avgValue, sumOfValues = 0;
for(int n = 0; n < count; n++){
sumOfValues = sumOfValues + theArray[n];
}
avgValue = sumOfValues/count;
return avgValue;
}
would become this if you did the conversion literally line-by-line with minimal changes
% function finds the average value in an array
function argValue = myAvg(theArray, count)
sumOfValues = 0;
for n = 0:count-1
sumOfValues = sumOfValues + theArray(n+1);
end
avgValue = sumOfValues/count;
end
Or you could recognize what this function is doing and vectorize it to something simpler
% function finds the average value in an array
function argValue = myAvg(theArray)
avgValue = mean(theArray);
end
And then of course you can see that the myAvg( ) function isn't needed at all ... you can simply use the MATLAB mean( ) function.
etc.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!