# how to sum data with condition

조회 수: 10 (최근 30일)
Berk Gulmez 2019년 10월 9일
답변: Daniel M 2019년 10월 10일
Hi everyone,
I have a dataset ;
x = [1 100; 1 101 ; 1 102; 2 109 ; 2 116 ; 2 118 ; 2 120 ; 3 103; 3 106]
I sorted data with respect to first column in ascending way while sorting second column again in ascending way.
Now, ı want to use functions those I prepared for this data with condition.
For instance, function 1 is used for [1 100] because it is first entry of value "1" in first column (calculation will be made with respect to column 2 value which is "100"). Then function 2 will continue until the end of "1" value in column 1.
when value "2" in column 1 enters, again function 1 calculates related value for "109" in column 2 and function2 will calculate other values for column2.
I cannot built correct loop for this calculation,
Thank you so much in advance.
Regards,

댓글을 달려면 로그인하십시오.

### 답변 (2개)

John D'Errico 2019년 10월 9일
Sorry, but it is a really bad idea to have separate functions for each case.
Just pass in the the first column element as an argument to the function that does the computations. Then it is just a branch inside the function, or perhaps a switch/case.
##### 댓글 수: 1이전 댓글 -1개 표시이전 댓글 -1개 숨기기
Berk Gulmez 2019년 10월 9일
Unfortunaltey, I cannot seperate the functions becuase the calculation will be connected to previous row value. For instance,
y = [1 100; 1 101 ; 1 102];
for the first row, function1 answer is 100 (similar to first row)
then in the second row function2 gives 101-100 = 1 value until the first column value turn into "2".

댓글을 달려면 로그인하십시오.

Daniel M 2019년 10월 10일
This is silly. But not difficult to implement.
x = [1 100; 1 101 ; 1 102; 2 109 ; 2 116 ; 2 118 ; 2 120 ; 3 103; 3 106];
y = x(:,1);
[~,startInds] = unique(y); % get the first index of each new number
y(setdiff(1:numel(y),b)) = 0; % set the other numbers to zero
for k = 1:size(x,1)
if y(k)
% code for function1(x(k,2));
else
% code for function2(x(k,2));
end
end

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by