solving logic , array and condition
1 view (last 30 days)
Show older comments
Hope you are doing well :)
I Have code below. I want to create an array with elements p = [5; 10; 10; 15; 15; 20; 20; 25; 25; 30; ]; and I want replace if statement if (stateCount(n)> 5 && stateCount(n)<= 10) with value from an array 5 and 10. How can I do that. Any tips will gladly welcome
% My previous code value comes from a csv file and store in a matrix name value
value =
2.2034000000000
5.9016000000000
24.0833000000000
25.1000000000000
10.3115000000000
15.3934000000000
20.8525000000000
30.7288000000000
21.4918000000000
6.7833000000000
7.3667000000000
16.7541000000000
34.2034000000000
StateCount = value;
stateHit = zeros(length(stateCount),20);
for n = 1:length(stateCount)
if (stateCount(n)<= 5)
stateHit(n,1) = 1;
else
if (stateCount(n)> 5 && stateCount(n)<= 10)
stateHit(n,2) = 1;
else
if (stateCount(n)>10 && stateCount(n)<= 15)
stateHit(n,3) = 1;
else
if (stateCount(n)> 15 && stateCount(n)<= 20)
stateHit(n,4) = 1;
else
if (stateCount(n)> 20 && stateCount(n)<= 25)
stateHit(n,5) = 1;
else
if (stateCount(n)> 25 && stateCount(n)<= 30)
stateHit(n,6) = 1;
end
end
end
end
end
end
end
I have change the code like that below but it doesn't work
% My modified code
value =
2.2034000000000
5.9016000000000
24.0833000000000
25.1000000000000
10.3115000000000
15.3934000000000
20.8525000000000
30.7288000000000
21.4918000000000
6.7833000000000
7.3667000000000
16.7541000000000
34.2034000000000
p = [5; 10; 10; 15; 15; 20; 20; 25; 25; 30; 30; 35;];
StateCount = value;
stateHit = zeros(length(stateCount),6);
for n = 1:length(stateCount)
for i=1:size(p,1)
if (stateCount(n)<= p(i,:) )
stateHit(n,1) = 1;
else
end
end
end
I can't get result in stateHit, matrix is all zero. Could please help me to find the problem in the code
Many thanks in advance
0 Comments
Answers (1)
Andrei Bobrov
on 29 May 2012
on first code
value =[...
2.2034000000000
5.9016000000000
24.0833000000000
25.1000000000000
10.3115000000000
15.3934000000000
20.8525000000000
30.7288000000000
21.4918000000000
6.7833000000000
7.3667000000000
16.7541000000000
34.2034000000000];
p0 = [0,5,10,15,20,25,30,35];
[f,f] = histc(value,p0+eps(100));
t = f~=0;
n = numel(value);
s = (1:n)';
stateHit = accumarray([s(t),f(t)],ones(nnz(t),1),[n,numel(p0)-1]);
on second code [EDIT]
stateCount = value;
p = [0;5;10; 15; 20; 25; 30; 35;];
stateHit2 = zeros(numel(stateCount),numel(p)-1);
for n = 1:length(stateCount)
for ii = 1:numel(p)-1
if stateCount(n) > p(ii) & stateCount(n)<= p(ii+1)
stateHit2(n,ii) = 1;
end
end
end
MORE variant
p1 = [p0(1:end-1);p0(2:end)];
stateHit3 = bsxfun(@le,value,p1(2,:)) & bsxfun(@gt,value,p1(1,:));
2 Comments
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!