how can i create a loop or function
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I have an Excel sheet with many columns and rows.
Say column “y” has serval “groups” of the same numbers but the groups are any length, I want to find the length of each group of the same numbers then use that information to sum the value of a vector in column “k” The following code works, for the 1st three groups but there are 20+ groups in the column and I need to find a more efficient way to get the answer
[numbers, strings, raw] = xlsread('BCT2.csv');
colk= numbers(:,11);
coly =numbers(:,25);
cf=coly;
EI=colk;
z=cf-cf(1); %%subtracts the first value from vector cf
idx = find(z<=0);
x=length(idx);
y=1:x;
A=sum(EI(y));
v=x+1;% the new starting point
z=cf-cf(v);
idx = find(z<=0); % indices
x1=length(idx);
d=x1-x;
ya=1:d;
B = sum(EI(ya))-A;
v2=x1+1;
z=cf-cf(v2);
idx = find(z<=0); % indices
x2=length(idx);
d1=x2-x1;
ya=1:d1;
C = sum(EI(ya))-B;
0 Kommentare
Akzeptierte Antwort
Stephen23
am 19 Mai 2015
Bearbeitet: Stephen23
am 19 Mai 2015
Then you could use accumarray, which is intended for exactly this kind of operation. Here is a simple example, where each run of identical digits in A is used to sum the values in B (e.g. the first run of A (the nines) sum the first B values [1,2,3] to give six:
>> A = [9,9,9,1,2,2,1,1]';
>> B = [1,2,3,4,5,6,7,8]';
>> X = cumsum([1;0~=diff(A)]);
>> accumarray(X,B)
ans =
6
4
11
15
>> [C,~,Y] = unique(A);
>> accumarray(Y,B)
ans =
19
11
6
>> C
C =
1
2
9
Note in this case the ones are summed together, even though they occur in two different runs in A.
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Cell Arrays finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!