Whats the difference when using [ ] and : ?

2 Ansichten (letzte 30 Tage)
Kaavya N
Kaavya N am 8 Dez. 2020
Beantwortet: Image Analyst am 8 Dez. 2020
reshape(key,2,[ ])
Can anyone explain how the above function works with an example

Antworten (3)

Adam
Adam am 8 Dez. 2020
Bearbeitet: Adam am 8 Dez. 2020
key = [1 2 3 4 5 6 7 8 9 10];
res = reshape( key, 2, [] );
would give
res = [ 1 3 5 7 9
2 4 6 8 10 ];
The [] indicates that the function should just use whatever is leftover as the remaining dimension - i.e. numel( key ) / 2 in this case. So the number of elements in key must be divisable by 2.

Ameer Hamza
Ameer Hamza am 8 Dez. 2020
reshape() work by taking the elements of the input matrix column-wise and arrange them into the shape you want. For example, help explain how it will rearrange the elements
>> key = [
1 6 11 16;
2 7 12 17;
3 8 13 18;
4 9 14 19;
5 10 15 20];
>> reshape(key, [], 2)
ans =
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
10 20

Image Analyst
Image Analyst am 8 Dez. 2020
The syntax is:
reshapedMatrix = reshape(key, desiredRows, desiredColumns);
If either desiredRows or desiredColumns is just empty brackets [] then it takes the one that is there and figures out what the other one should be for you, as a convenience so that you don't have to do the math yourself.
For example, since you input 2 for desiredRows, then if you use [] for desiredColumns, it will compute desiredColumns for you like this:
desiredColumns = numel(key) / 2;
It's a nice convenience, you just have to make sure that you'll have a square matrix (no ragged last row or column just partially filled with numbers. In other you must have numel(key) be a multiple of desiredRows (2 in your example). So
key = 1:6
rk = reshape(key, 2, []) % 2 rows-by-3 columns
works:
key =
1 2 3 4 5 6
rk =
1 3 5
2 4 6
while
key = rand(1, 5);
reshapedMatrix = reshape(key, 2, []); % Throws error
doesn't work because 5 is not a multiple of 2 and you can't have a matrix with the first two columns having 2 rows and the rightmost column having only one row. No "ragged edges" allowed.
key =
1 2 3 4 5 6
rk =
1 3 5
2 4 Can't have nothing in the lower right corner

Kategorien

Mehr zu Write C Functions Callable from MATLAB (MEX Files) finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by