0

say I have got two cell arrays a, b:

for k=1:3
    a{k} = nan(3, k);
end
b = {ones(1, 1), ones(1, 2), ones(1, 3)};

how I assign each cell in b into the second line of each cell of a?

Gideon Kogan
  • 662
  • 4
  • 18

1 Answers1

1

Just have a loop:

for i=1:size(a,2)
    a{i}(2,:) = b{i}
end

If a and b are small, you can use deal:

[a{1}(2,:) a{2}(2,:) a{3}(2,:)] = deal(b{:});
Paolo
  • 21,270
  • 6
  • 38
  • 69
  • this is answering my question but considering that I am asking a minimal question, would it solve a case where k=1:50? – Gideon Kogan May 04 '20 at 12:03
  • 2
    Although I honestly think you should just do a simple loop – Paolo May 04 '20 at 12:10
  • I dont feel good with the eval solution but you are probably right about the loop solution. – Gideon Kogan May 04 '20 at 12:15
  • I just wanted to show that that is one option. I personally don't see an alternative to this or the loop. I don't think you are going to find a different "magic" oneliner. Assigning stuff to comma separated outputs in this scenario is tricky. – Paolo May 04 '20 at 12:17
  • 1
    I'd be very cautious with suggesting `eval`, especially without any warnings. See [this answer of mine](https://stackoverflow.com/a/32467170/5211833) and references therein on why it's best to avoid it whenever possible. Gist is: hard to debug errors and slow execution due to disabling of the JIT. – Adriaan May 04 '20 at 12:17
  • Of course, its just for fun. OP should just have a loop, since that is the simplest and most readable solution. – Paolo May 04 '20 at 12:20