Save two variables generated within a for loop
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi. I am trying to save the two variables (x_out and y_out) present in the for loop (see inside the function 'example.m', line 34 and 35).
How can I do this?
Attached you will find the .txt files to use the function.
X = importdata('X.txt');
IDX = importdata('IDX.txt');
example(X, IDX);
댓글 수: 0
채택된 답변
Zahrah Walid
2022년 12월 3일
Variables generated inside a function are locl variables inside the function only.
you can return the wanted variables from your function as follows:
function [x_out, y_out]=example(X, IDX)
%your function body as you provide
end
and when calling the function from the main program, you just put x_out and y_out values in your wanted variable in main program, i.e.:
X = importdata('X.txt');
IDX = importdata('IDX.txt');
[x,y] = example(X, IDX); %your x_out value is assigned into x variable and y_out value is assigned into y variable.
댓글 수: 3
Zahrah Walid
2022년 12월 3일
You just have to define px and py as follows in the function:
px(i+1,k) = x_out;
py(i+1,k) = y_out;
It's preferred to setup the second figure by the same settings of the first one to avoid pseudo differences.
figure()
plot(px,py,'*k'); % I want to get the second figure but with all the * blacks (as in the first plotted figure)
axis equal; %to be the same ratio
xlim([70 430])
ylim([150 300])
and this is the whole code, I have tried it after modification and I think it works as you want:
X = importdata('X.txt');
IDX = importdata('IDX.txt');
%example(X, IDX);
[px, py] = example(X, IDX);
figure()
plot(px,py,'*k'); % I want to get the second figure but with all the * blacks (as in the first plotted figure)
axis equal;
xlim([70 430])
ylim([150 300])
function [px, py] = example(X, IDX)
k=max(IDX);
Colors=hsv(k);
Legends = {};
n = 1;
for i=0:k
Xi=X(IDX==i,:);
if i~=0
Style = 'x';
MarkerSize = 8;
Color = Colors(i,:);
% Legends{2*n-1} = ['Cluster #' num2str(i)];
% Legends{2*n} = ['Boundary # ' num2str(i)];
n = n+1;
else
Style = 'o';
MarkerSize = 6;
Color = [0 0 0];
if ~isempty(Xi)
Legends{end+1} = 'Noise';
end
end
if ~isempty(Xi)
x_temp = Xi(:,1);
y_temp = Xi(:,2);
s = 1;
k = boundary(x_temp,y_temp,s);
x_out = x_temp(k);
y_out = y_temp(k);
px(i+1,k) = x_out;
py(i+1,k) = y_out;
plot(x_temp,y_temp,Style,'MarkerSize',MarkerSize,'Color',Color);
hold on
plot(x_out,y_out,'*k');
hold on
end
hold on;
end
hold off;
axis equal;
grid on;
legend(Legends);
legend('Location', 'NorthEastOutside');
xlim([70 430])
ylim([150 300])
end
figure 1
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1217722/image.png)
figure 2
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1217727/image.png)
Is this what you want?
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Title에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!