Combine arrays of different dimensions

148 Ansichten (letzte 30 Tage)
minu pilvankar
minu pilvankar am 3 Sep. 2019
Kommentiert: Adam Danz am 22 Feb. 2022
Hello,
If I have 2 data sets of different dimensions.
xdata1 = [1 2 3 4] ; ydata1 = [2 3 4 5]
xdata2 = [1 2 3 4 5]; ydata2 = [7 4 9 11 12]
Can I create a combined data set for xdata and ydata such that:
xdata = [1 2 3 4; 1 2 3 4 5]
ydata = [2 3 4 5; 7 4 9 11 12];
I tried with initializing an array of zeros or NaN for xdata and ydata and then replace with xdata1 and ydata1 elements. But I do not want zeros or NaN in the array as I am using these numbers for further calculation which gives error with zero or NaN elements. I basically need to store all the xdatas and ydatas together and then call each colum (representing each data set) individually later for calculation.
Can you help?

Akzeptierte Antwort

Adam Danz
Adam Danz am 3 Sep. 2019
Bearbeitet: Adam Danz am 6 Sep. 2019
You cannot have a matrix with varying row lenght.
One alternative is to create a padded array where NaN values fill the ends of shorter rows.
xdata = [1 2 3 4 NaN; 1 2 3 4 5];
ydata = [2 3 4 5 NaN; 7 4 9 11 12];
"I do not want zeros or NaN in the array as I am using these numbers for further calculation which gives error with zero or NaN elements."
To deal with that, many Matlab functions automatically ignore NaN values or have flags that can be set to ignore NaN values. For the functions that do not have this option, you can use isnan() to identify non-NaN values so that NaNs are ignored.
mean(xdata,2,'Omitnan')
An alternative is to pack the vectors into a cell array.
xdata = {[1 2 3 4]; [1 2 3 4 5]};
ydata = {[2 3 4 5]; [7 4 9 11 12]};
and to use cellfun() to process each element of the array.
cellfun(@(x)mean(x,'omitnan'),xdata)
[addendum]
"I basically need to store all the xdatas and ydatas together and then call each column"
I think the first method (padding) would work best.
  2 Kommentare
Nimasha Pilippange
Nimasha Pilippange am 19 Feb. 2022
I have 2 matrices as A=[ 1 2 3 4 5] and B= [ 6 7 8 9 10] , How can I combine them so I can get C=[1 6 2 7 3 8 4 9 5 10]. I need for a large matrix. But first I will start with a small matrix.
Can anyone help?
Adam Danz
Adam Danz am 22 Feb. 2022
It looks like you found an answer to your question.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by