Subtraction of cell values with a fixed value
4 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
DGM
on 4 Jun 2021
Edited: DGM
on 7 Jun 2021
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 Comments
DGM
on 7 Jun 2021
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.
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!