Use loop for indexing

조회 수: 5 (최근 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