0
$\begingroup$

I have an empty vector like U = {}. In an iteration, I get u1 = {a, b} and I want to put the vector in U to have {{},{a,b}}. I can do this simply with U = {U, u1} command. But in another iteration, I get for example u2={c} and want to have {{},{a,b},{c}}. How can I do this?

If I use the same command as before: U = {U, u2} I will have {{{},{a,b}},{c}} but I want to have only {{},{a,b},{c}}

Thanks All

$\endgroup$
6
  • 1
    $\begingroup$ What have you tried? $\endgroup$ Commented May 25, 2023 at 18:19
  • 1
    $\begingroup$ Maybe use Append. But there are functions like NestList and FoldList that might give you what you want "for free". Would need to see more details of what you're doing. $\endgroup$
    – lericr
    Commented May 25, 2023 at 18:31
  • $\begingroup$ I have deleted my answer because I don't think I understand the question. Does u have a specific structure? $\endgroup$
    – ydd
    Commented May 25, 2023 at 19:12
  • 1
    $\begingroup$ Since you already have s and presumably lp is defined, you could do this: FoldList[Append[#1, s[#2]] &, {}, Range[lp]] $\endgroup$
    – lericr
    Commented May 25, 2023 at 19:26
  • 1
    $\begingroup$ The questions should demonstrate some effort and it would be best if you could show us what you have already tried. Please edit your question to update accordingly! $\endgroup$
    – bmf
    Commented May 26, 2023 at 7:57

1 Answer 1

1
$\begingroup$

This code does what I think you want based on your question

ClearAll[append];
(* define modified Append function *)
append[{}, ui_] := {{}, ui};
append[u_, ui_] := Append[u, ui];
U = {}; u1 = {a,b}; u2 = {c};
U = append[U, u1]
(* {{}, {a, b}} *)
U = append[U, u2]
(* {{}, {a, b}, {c}} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.