Subtraction of cell values with a fixed value
조회 수: 9 (최근 30일)
이전 댓글 표시
Hello,
I'm trying to subtract the fixed number 389.387 from every cell element and then find the smallest one in each group. My code so far:
value_r = value_r';
grouped = mat2cell( value_r, 1, diff( [0, find(diff(row_r) ~= 1), length(row_r)] ));
%% grouped is a cell with [1x19 double] [1x2 double] [1x3 double] [1x2 double] [1x2 double] [1x1 double] [1x3 double] [1x2 double] [1x2 double] [1x3 double]
for i = 1:length(b)
difference(i) = abs(grouped{i} - 389.387);
end
But I keep getting the error code "Unable to perform assignment because the size of the left side is 1-by-1 and the size of the right side is 1-by-19.". The for loop works, but i can't safe the results in another variable. Any ideas?
I'm using Matlab R2020b for academic use
댓글 수: 0
채택된 답변
DGM
2021년 6월 4일
편집: DGM
2021년 6월 7일
You could use cellfun() if you wanted.
s = [1 39];
A = randi([1 20],s(1),s(2));
k = 100; % the number to subtract
blocksizes = [19 2 3 2 2 1 3 2 2 3];
C = mat2cell(A,s(1),blocksizes)
D = cellfun(@(x) x-k,C,'uniformoutput',false);
E = cell2mat(cellfun(@min,D,'uniformoutput',false))
% if intermediate result D is not needed
F = cell2mat(cellfun(@(x) min(x-k),C,'uniformoutput',false))
% minimizing first is faster
G = cell2mat(cellfun(@min,C,'uniformoutput',false))-k
Lastly, the fastest way would be to avoid cell operations. If all the block sizes are the same, you can do that like this.
H = min(reshape(A(1:36),4,9))-k % note all the block sizes are identical
댓글 수: 3
DGM
2021년 6월 7일
Ah yeah. I forgot about that. I got this mixed up with about three similar answers on the same day. The last example really only works with fixed block sizes. I imagine you could jump through some hoops using NaN padding, but I don't see a reason to actually recommend it.
I edited for clarity and went ahead and used the block sizes in your question for the cell array example.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!