Use loop for indexing
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
Geoff Hayes
el 24 de Jun. de 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.
Respuestas (1)
Jan
el 24 de Jun. de 2017
Editada: Jan
el 24 de Jun. de 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
0 comentarios
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!