Help With Converting C++ Code To MATLAB

2 views (last 30 days)
Yawar Khalid
Yawar Khalid on 15 Mar 2018
Answered: Manan Mishra on 2 Apr 2018
I am new to MATLAB and need help converting a c++ code to matlab. I tried using the mex method but it didnt work out. Anyways the code involves a loop to access one dimensional array. The code is as below :
int myarr[] = {1,2,3,4,5};
for (int i=0;i<5;i++)
{
if (i==0)
{
myarr[i] = myarr[i]/65536;
}
else
{
myarr[i] = myarr[i]/65536 + myarr[i-1];
}
}
for (i=0;i<5;i++)
{
cout << myarr[i]; // This is the main part, i want to be able to output index along with the array name, in this
case myarr
}
return 0;
}
Any help would be much appreciated.
Thanks
  4 Comments
James Tursa
James Tursa on 15 Mar 2018
Thanks, but again I will point out that if you have 8-bit unsigned integers then the max value they could be is 65535. So if you do an integer divide by 65536 all the results will be identically 0. So we are back where we started. Nothing you have posted thus far will give anything other than identical 0 results.
Yawar Khalid
Yawar Khalid on 16 Mar 2018
Well it was a long night so forgive me for not correcting 65536 to 65535. I did edit my code above now so maybe you can help me now. The problem isnt getting answer that is 0. I want an output like this :
The values for the array WITH INDEXES are :
myarr0 = 0.123
myarr1 = 0.234
myarr2 = 0.345
myarr3 = 0.456
myarr4 = 0.567
I hope now you understand what I want. The c++ code and desired output can be seen here : http://codepad.org/oX2OABf8

Sign in to comment.

Answers (1)

Manan Mishra
Manan Mishra on 2 Apr 2018
I would like to point out a difference between the code you shared here and in the 'codepad' link.
Here, you specified your array as int:
int myarr[] = {10,100,1000,10000,100000}
whereas in the 'codepad' link, you specified it as a float:
float myarr[] = {10,100,1000,10000,100000};
This might be the reason of confusion for James also, as an 'int' array would give all zeros in 'myarr'.
However, you can do the same thing in MATLAB as follows:
myarr = [10,100,1000,10000,100000];
format long;
myarr = cumsum(myarr/65535);
disp("The values of the array WITH THE INDEXES ARE :")
for i=1:length(myarr)
fprintf('myarr%d = %d \n',i,myarr(i))
end

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!