Use loop for indexing

2 次查看(过去 30 天)
shawin
shawin 2017-6-24
编辑: Jan 2017-6-24
I'm trying to retriev an index from data by passing labels from 1 to 2 but the for loop is not changing?
clc;
clear all;
close all;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
c=2;
labels =[2,1,2,1,2,1,2,1,2,2];
data =[-26.152,0.59028;2.0480,1.1151;-16.680,0.704710;8.2308,1.1567;-14.1760,-0.879840;
7.81450,0.7927;-20.220,0.992;8.921,0.822;-16.507,0.5297;-11.212,-1.6457];
colors={'r.' 'gx' 'b+' 'ys' 'md' 'cv' 'k.' 'r*' 'g*' 'b*' 'y*' 'm*' 'c*' 'k*' };
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i=1:c
index = find(labels == i);
if ~isempty(index)
dat=data(index,:);
plot(dat(:,1),dat(:,2),colors{i})
end
end
for i=1:c
index=find(labels == 1);
f0(index,i)=1;
end
result.data.f=f0;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
i=2 not 1, 2
  1 个评论
Geoff Hayes
Geoff Hayes 2017-6-24
shawin - why do you expect i to be 1,2? You have two for loops, so when the second one iterates over 1 and 2 so it will be assigned a value of 2 when the loop completes. Try using the debugger to step through the code and see this.

请先登录,再进行评论。

回答(1 个)

Jan
Jan 2017-6-24
编辑:Jan 2017-6-24
Use the auto-indentation to get clear code:
for i=1:c
index = find(labels == i);
if ~isempty(index)
dat=data(index,:);
plot(dat(:,1),dat(:,2),colors{i})
end
end
for i=1:c
index=find(labels == 1);
f0(index,i)=1;
end
Perhaps "i=2 not 1, 2 " means the second loop. Is "labels == 1" a typo and you meant "labels == i" as in the first loop?
By the way: "logical indexing" is faster:
for k = 1:c
index = (labels == k); % Without FIND
f0(index, k) = 1;
end

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by