Subtraction of cell values with a fixed value
5 次查看(过去 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!