Can someone explain this simple matlab code to me

1 view (last 30 days)
Can you please explain the following. New to matlab
Y = load('test.txt');
set = [Y(1:0,:);Y(101:end,:)];
  1 Comment
dpb
dpb on 3 Aug 2017
Start answered on the code as written syntactically; I'd posit it is a typo and was intended as something like
set = [Y(1:10,:);Y(101:end,:)];
in which case what the result is would be the first 10 and last M rows of the array Y. Often one sees such code to just later be able to visualize a small portion of a much larger array by taking a small section and the first and last few rows are generally the most interesting...a more general form would be to write
set = [Y(1:N,:);Y(end-(N-1):end,:)];
to pick up the first and last N records.
The comment on set is very important--do not alias builtin Matlab function names; trouble is bound to ensue.

Sign in to comment.

Accepted Answer

Benjamin Attal
Benjamin Attal on 3 Aug 2017
Welcome to matlab! In general, the matlab documentation can be a very helpful tool for understanding and writing code. For example, by looking up the 'load' function on the matlab documentation site, or by typing
help load
into the matlab command prompt, you can find that
Y = load('test.txt');
creates a structure array Y that holds all of the variables stored in 'test.txt'. For more information about what a struct is , how to save variables into a file , and more you can also look at the docs.
As Star Strider mentioned, the line
set = [Y(1:0,:);Y(101:end,:)];
Looks like it might have a couple of problems. Maybe you meant something like
temp = [Y(1:50,:);Y(101:end,:)];
The expression
Y(1:50,:)
will get the first 50 rows of the structure array Y (1:50 in the first index denotes choosing the first 50 rows, and the colon in the second index denotes choosing all of the columns).
The expression
Y(101:end,:)
will get the 101st through the last rows of the structure array Y (101:end in the first index denotes choosing the 101st through the last rows, and the colon in the second index denotes choosing all of the columns). For more information about how indexing works in matlab, look at: https://www.mathworks.com/company/newsletters/articles/matrix-indexing-in-matlab.html
Doing
[Y(1:50,:);Y(101:end,:)];
vertically concatenates the first 50 rows, and the 101st through the last rows. So it effectively creates a structure array where the first 50 rows of Y are placed on top of the 101st through the last rows of Y. See https://www.mathworks.com/help/matlab/ref/vertcat.html for more information about vertical concatenation.
Hope this helps!

More Answers (0)

Categories

Find more on Data Type Identification in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!