What is going wrong with this code

wves=xlsread('Data_all.xlsx','Wave_data');
c=wves(3:end,Waves);
disp(c)
WH01=0;
WH23=0;
WH45=0;
WH67=0;
WH89=0;
WH1011=0;
WH1213=0;
for i = 0:1:498
if (c(i) == 0) || (c(i) == 1)
WH01=WH01+1;
elseif (c(i) == 2) || (c(i) == 3)
WH23=WH23+1;
elseif (c(i)==4) || (c(i)==5)
WH45=WH45+1;
elseif (c(i)==6) || (c(i)==7)
WH67=WH67+1;
elseif (c(i)==8) || (c(i)==9 )
WH89=WH89+1;
elseif (c(i)==10) || (c(i)==11)
WH1011=WH1011+1;
elseif (c(i)==12) || (c(i)==13 )
WH1213=WH1213+1;
end
end

4 Comments

Replace c(i) with c(i+1), or start i in the for loop from 1 rather than 0. MATLAB indexing is 1 based.
Also Waves does not appear to be defined.
The Waves are defined in the beggining of the complete code

Answers (2)

>> n=arrayfun(@(i1,i2) sum(iswithin(c,i1,i2)),0:2:13,1:2:13)
n =
14 15 10 14 14 17 16
>> type iswithin
function flg=iswithin(x,lo,hi)
% returns T for values within range of input
% SYNTAX:
% [log] = iswithin(x,lo,hi)
% returns T for x between lo and hi values, inclusive
flg= (x>=lo) & (x<=hi);
>>
Presuming the magic number 498 is numel(c)-1
This should be a job for one of the histogram functions, but there's no way Io make one of them use the inclusive bin edges to count the two end points within the bin even for nonoverlapping data

2 Comments

h = histcounts(c, 0:2:14)
The first bin corresponds to [0, 2) which for integer c data means it captures c = 0 and c = 1. The last bin corresponds to [12, 14] which captures c = 12 and c = 13 (and would capture c = 14, but the question implies that c only contains integer values between 0 and 13 inclusive.)
I thought I had done that, Steven...[search command history....] Oh! I had tried to use 1 to capture inclusive. I don't see why my attempt at using a tolerance -- oh, I do now.
I just wasn't thinking about the [0, 2) definition correctly.
Thanks for setting me straight...
Alternate solution:
ix=kron([1:numel(0:13)/2].',ones(2,1));
n=accumarray(ix(c+1),ones(size(c)));
>> n
n =
14
15
10
14
14
17
16
>>

This question is closed.

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!