# Convert Python code (loop) to MATLAB

14 views (last 30 days)
Iliqe on 18 Feb 2022
Hello everyone, here I have some code from Python, could you please help to convert it to Matlab.
mylist = list(range(100)) # for demo
folds = [mylist[x:x+10] for x in range(0, len(mylist),10)] # create 10 folds
# Iterate all folds
counter = 0
for i in range(len(folds)):
counter += 1
testing = folds[i]
training = folds[:i] + folds[i+1:]
print(f"Iteration {counter}, for testing: {testing},\n for training: {training} \n") # for check

Abolfazl Chaman Motlagh on 18 Feb 2022
it depend on what class you want folds be. (an array, a cell , ... )
for example if all elements in list have same lenght, here 10;
you can use 2D array:
folds = reshape(1:100,[10 10])'
for i=1:10
testing = folds(i,:);
training = folds([1:i-1 i+1:10],:);
disp(['iteration ' num2str(i) , ' for testing: ' num2str(testing)])
disp('for training: '); disp(num2str(training));
end
for cell :
for i=1:10
folds{i,1} = (i-1)*10+1:i*10;
end
for i=1:10
testing = folds{i}; % as an array , folds(i) as a cell
training = folds(setdiff(1:10,i)); % as a cell
disp(['iteration ' num2str(i) , ' for testing: ' num2str(testing)])
disp('for training: '); disp(num2str(cell2mat(training))); % cause training is cell you should convert it to array first
end
##### 1 CommentShowHide None
Iliqe on 20 Feb 2022
Yep, the class of folds will be cell, sorry for not notifying about it.
But your answer covers even more than I asked, many thanks, it works well!

### More Answers (1)

Dana Albojoq on 10 Apr 2022
hello I have Python code , can you help to convert it to Matlab.
import cv2
import numpy as np
def pixelVal(pix, a1, b1, a2, b2):
if (0 <= pix and pix <= a1):
return (b1 / a1)*pix
elif (a1 < pix and pix <= a2):
return ((b2 - b1)/(a2 - a1)) * (pix - a1) + b1
else:
return ((255 - b2)/(255 - a2)) * (pix - a2) + b2
a1 = 70
b1 = 0
a2 = 140
b2 = 255
pixelVal_vec = np.vectorize(pixelVal)
contrast_stretched = pixelVal_vec(img, a1, b1, a2, b2)
cv2.imwrite('contrast_stretch.jpg', contrast_stretched)
##### 1 CommentShowHide None
Ali Muhammad Hassaan on 11 Oct 2022
https://mathesaurus.sourceforge.net/matlab-numpy.html