MATLAB Answers

0

Help Converting C++ to MATLAB.

Asked by Farid Abdurahmanov on 15 Apr 2019
Latest activity Commented on by darova
on 15 Apr 2019
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 Comment

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

Sign in to comment.

1 Answer

Answer by James Tursa
on 15 Apr 2019

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 Comments

Sign in to comment.