Use loop for indexing

2 views (last 30 days)
shawin
shawin on 24 Jun 2017
Edited: Jan on 24 Jun 2017
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 Comment
Geoff Hayes
Geoff Hayes on 24 Jun 2017
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.

Sign in to comment.

Answers (1)

Jan
Jan on 24 Jun 2017
Edited: Jan on 24 Jun 2017
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

Community Treasure Hunt

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

Start Hunting!