Convert Python code (loop) to MATLAB

조회 수: 7 (최근 30일)
Iliqe
Iliqe 2022년 2월 18일
댓글: Ali Muhammad Hassaan 2022년 10월 11일
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
Abolfazl Chaman Motlagh 2022년 2월 18일
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
Ali Muhammad Hassaan 2022년 10월 11일
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