Convert Python code (loop) to MATLAB

5 次查看(过去 30 天)
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
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 个评论
Iliqe
Iliqe 2022-2-20
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!

请先登录,再进行评论。

更多回答(1 个)

Dana Albojoq
Dana Albojoq 2022-4-10
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
img = cv2.imread('sample.jpg')
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 个评论
Ali Muhammad Hassaan
Hi, this page might be helpful for you.
https://mathesaurus.sourceforge.net/matlab-numpy.html

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Call Python from MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by