How can I correctly use two "for loops" and one "if statement" to insert selected data into a cell array?
조회 수: 3 (최근 30일)
이전 댓글 표시
I have the following variables: Matrix A with the size 75x1, Matrix B with the size 2400x2, Cell C with the size 75x1.
I am trying to insert B(i,2) into C{j}, if it passes the condition (A(j,1)-0.25)<B(i,1)<(A(j,1)+0.25). I am doing this so that later I can take the averages of each element of C. The code I have written for this is not working the way it should. It puts all the elements of B(:,2) into each cell of C. Any help would be appreciated. Thanks in advance!
C = cell(75,1);
for i = 1:75
for j = 1:2400
if (A(i,1)-0.25) < B(j,1) < (A(i,1)+0.25)
C{i}(end+1)= B(j,2);
end
end
end
D = cell(size(C));
for o = 1:numel(D)
D{o} = mean(C{o});
end
D = cell2mat(D);
댓글 수: 0
채택된 답변
Guillaume
2017년 7월 20일
편집: Guillaume
2017년 7월 20일
The correct way to do what you want is not to use loops and if statements but operate on whole matrices at once. It will be a lot faster.
However, the only reason your code does not work is because:
x < y < z
is not the way you write comparison in matlab (and most computer languages). The correct way is
x < y && y < z
What you have written compares x to y. That produces one of two results, either 0 (false) or 1 (true). It then compares that 0 or 1 result to z. Hence, if z is greater than 1, then your test will always return true regardless of the value of x and y.
But, as said, the best way to do what you want, assuming R2016b or later:
inrange = abs(B(:, 1)' - A) < 0.25; %compare all of B with all of A at once
D = sum(inrange .* B(:, 2)', 2) ./ sum(inrange, 2);
If on earlier than R2016b:
inrange =abs(bsxfun(@minus, B(:, 1)', A)) < 0.25;
D = sum(bxsfun(@times, inrange, B(:, 2)'), 2) ./ sum(inrange, 2);
댓글 수: 0
추가 답변 (1개)
the cyclist
2017년 7월 20일
A(i,1)-0.25) < B(j,1) < (A(i,1)+0.25
is not going to do what you expect. This needs to be written as two separate conditions that are both checked:
A(i,1)-0.25) < B(j,1) & B(j,1) < (A(i,1)+0.25
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Spreadsheets에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!