Save two variables generated within a for loop
1 回表示 (過去 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
figure 2
Is this what you want?
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Annotations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!