Subtraction of cell values with a fixed value

8 Ansichten (letzte 30 Tage)
Bruce Rogers
Bruce Rogers am 4 Jun. 2021
Kommentiert: Bruce Rogers am 7 Jun. 2021
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

Akzeptierte Antwort

DGM
DGM am 4 Jun. 2021
Bearbeitet: DGM am 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)
C = 1×10 cell array
{[7 19 4 4 16 7 2 16 4 15 3 17 17 20 2 13 17 16 1]} {[1 5]} {[3 12 5]} {[3 12]} {[19 7]} {[13]} {[19 10 5]} {[9 15]} {[20 19]} {[19 14 3]}
D = cellfun(@(x) x-k,C,'uniformoutput',false);
E = cell2mat(cellfun(@min,D,'uniformoutput',false))
E = 1×10
-99 -99 -97 -97 -93 -87 -95 -91 -81 -97
% if intermediate result D is not needed
F = cell2mat(cellfun(@(x) min(x-k),C,'uniformoutput',false))
F = 1×10
-99 -99 -97 -97 -93 -87 -95 -91 -81 -97
% minimizing first is faster
G = cell2mat(cellfun(@min,C,'uniformoutput',false))-k
G = 1×10
-99 -99 -97 -97 -93 -87 -95 -91 -81 -97
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
H = 1×9
-96 -98 -97 -98 -99 -97 -97 -95 -91
  3 Kommentare
DGM
DGM am 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.
Bruce Rogers
Bruce Rogers am 7 Jun. 2021
No problem, you're right, i can just count first the number of groups and the length of the vector and then it's all variable! Thanks DGM!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by