Asked by Naime
on 18 Jan 2019

I have C={[-8;-5],[1;-4;-5;-5;-5],[-3;-5]}

I want to get this result CC={[0;-8;-5],[0;1;-4;-5;-5;-5],[0;-3;-5]}

I use this code, but do not works c = cellfun(@(x)(x(0)==0), a, 'UniformOutput', false);

Answer by Stephen Cobeldick
on 18 Jan 2019

Edited by Stephen Cobeldick
on 18 Jan 2019

Accepted Answer

cellfun(@(v)[0;v],C,'uni',0)

And checking:

>> C = {[-8;-5],[1;-4;-5;-5;-5],[-3;-5]};

>> CC = cellfun(@(v)[0;v],C,'uni',0);

>> CC{:}

ans =

0

-8

-5

ans =

0

1

-4

-5

-5

-5

ans =

0

-3

-5

Stephen Cobeldick
on 18 Jan 2019

index2 means first element of [2,3,4] means 2

index3 means second element of [2,3,4] means 3

index4 means third element of [2,3,4] means 4

This was confusing because you wrote the same index in two different ways. It helps to be consistent, ratther than using different names for the same thing:

CC{2}(index5)=1 B(5)=- -9.1 1-10.1=-9.1

% ^^^^^^ <-> ^

In any case, here is one way to get those values that you wanted:

>> tmp = cellfun(@(c,i)c+B(i(1)),CC,index,'uni',0);

>> idx = [index{:}];

>> newB = zeros(1,max(idx));

>> newB(idx) = vertcat(tmp{:})

newB =

0.00000 -5.10000 -13.10000 -10.10000 -9.10000 -14.10000 -13.10000 -13.00000 -15.10000 -15.10000 -15.10000

Stephen Cobeldick
on 19 Jan 2019

Lets split this line:

tmp = cellfun(@(c,i)c+B(i(1)),CC,index,'uni',0);

into two lines:

fun = @(c,i)c+B(i(1));

tmp = cellfun(fun,CC,index,'uni',0);

where the first line defines an anonymous function:

For each of the corresponding cell contents in CC and index, that anonymous function will calculate

c+B(i(1))

where c and i are the function inputs, as provided by cellfun, i.e. are the cell contents of CC and index. So this is equivalent to:

CC{1}+B(index{1}(1))

CC{2}+B(index{2}(1))

CC{3}+B(index{3}(1))

... etc.

Naime
on 19 Jan 2019

Thank you so much.

Sign in to comment.

Answer by Image Analyst
on 19 Jan 2019

Granted, cellfun() is a bit cryptic, so if you want a simple, easy to understand intuitive method, just use for loops:

C = {[-8;-5],[1;-4;-5;-5;-5],[-3;-5]};

for col = 1 : size(C, 2)

for row = 1 : size(C, 1)

existingContents = C{row, col}; % Get existing vector

C{row, col} = [0; existingContents]; % Prepend 0

end

end

celldisp(C)

Sure, it's not as compact, and slightly slower (a millsecond or so for that array) but it's more intuitive.

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.