Is there a way to call a part of a function using an index?
조회 수: 13(최근 30일)
표시 이전 댓글
I have a function that I call several times:
plot(position6(1),position6(2),'r+', 'MarkerSize', 100, 'Color', 'w');
h = images.roi.Circle(gca,'Center', position6,'Radius',100, 'Color', 'w', 'FaceAlpha', 0);
Where "position6" is one of N positions defined. Currently, I am manually defining each of them and writing these two lines of code for each position vector (which is in a matrix of vectors). Is there any way to condense this to make it neater, such that I can refer to each instance of the code using the index of the vector matrix? Perhaps with a function?
For example:
myfunc(6)
returns:
plot(position6(1),position6(2),'r+', 'MarkerSize', 100, 'Color', 'w');
h = images.roi.Circle(gca,'Center', position6,'Radius',100, 'Color', 'w', 'FaceAlpha', 0);
Thanks. Here's the full verson of the relevant code segment.
[rows, columns, numberOfColorChannels] = size(img);
figure;
imshow(img);
position1 = [(columns*0.75), (rows*0.5)];
position8 = [(columns*0.75), (rows*0.25)];
position9 = [(columns*0.75), (rows*0.75)];
position2 = [(columns*0.25), (rows*0.5)];
position6 = [(columns*0.25), (rows*0.25)];
position7 = [(columns*0.25), (rows*0.75)];
position3 = [(columns*0.5), (rows*0.5)];
position4 = [(columns*0.5), (rows*0.25)];
position5 = [(columns*0.5), (rows*0.75)];
position = {position1, position2, position3, position4, position5, position6, position7, position8, position9};
hold on;
plot(position{6}(1),position{6}(2),'r+', 'MarkerSize', 100, 'Color', 'w');
h = images.roi.Circle(gca,'Center', position{6},'Radius',100, 'Color', 'w', 'FaceAlpha', 0);
채택된 답변
Rik
2021년 3월 23일
Reposting as answer:
For the reasons set out in the answer by Steven (and the subsequent comments), numbering your variables in not ideal. If you use arrays, you can index them:
columns = 80;
rows = 24;
[c,r]=ndgrid([0.75 0.25 0.5],[0.5 0.25 0.75]);
position=[columns*c(:) rows*r(:)];
position=mat2cell(position,ones(1,size(position,1)),2);
disp(position.')
myfun(position{6})
function h=myfunc(pos)
plot(pos(1),pos(2),'r+', 'MarkerSize', 100, 'Color', 'w');
h = images.roi.Circle(gca,'Center', pos,'Radius',100, 'Color', 'w', 'FaceAlpha', 0);
if nargout==0,clear,end
end
댓글 수: 0
추가 답변(1개)
Steven Lord
2021년 3월 22일
Do you mean you want to plot position6(1) versus position6(2) in the first call, position6(3) versus position6(4) in the second, etc.? That's easy, a simple for loop (incrementing by two) would be easiest.
for k = 1:2:10
fprintf("Processing elements %d and %d.\n", k, k+1)
end
Or do you want to plot position6(1) versus position6(2) in the first call, position7(1) versus position7(2) in the second, position8(1) versus position8(2) in the third, etc.?
참고 항목
범주
Find more on Graphics Object Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!