How to separate an array into 3

18 次查看(过去 30 天)
gmltn1212
gmltn1212 2020-5-28
Hi I am trying to divide one array into 3 arrays
let's say A = [11 22 33 44 55 66 77 88 99]
I want to divide A like this:
B = [11 33 55 77]
C = [22 44 66 88]
D = [99]
This is just an example...Could you come up some idea for this?

回答(2 个)

Stephen23
Stephen23 2020-5-29
>> A = [11,22,33,44,55,66,77,88,99];
>> B = A(1:2:end-1)
B = 11 33 55 77
>> C = A(2:2:end-1)
C = 22 44 66 88
>> D = A(end)
D = 99

Brent Kostich
Brent Kostich 2020-5-28
A simple way is by indexing, like so:
A = [11 22 33 44 55 66 77 88 99];
B = A([1, 3, 5, 7]);
C = A([2, 4, 6, 8]);
D = A(9);
If you are looking for a more general solution than explicit indexing, then you will have to provide more parameters for your problem.
  2 个评论
gmltn1212
gmltn1212 2020-5-28
Thank you for solution.
But what if A always contains odd number of elements and B and C should take every other elements (explained above) and D is required to take the last element of the array?
for D i figured out the function: lastDigit = A(end);
Could you give me something like this?
Brent Kostich
Brent Kostich 2020-5-29
If you wanted to filter by even and odd, then you should have specified that in your question. That operation is not difficult though, see Stephen Cobeldick's answer.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by