Whats the difference when using [ ] and : ?
조회 수: 2 (최근 30일)
이전 댓글 표시
reshape(key,2,[ ])
Can anyone explain how the above function works with an example
댓글 수: 0
답변 (3개)
Adam
2020년 12월 8일
편집: Adam
2020년 12월 8일
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.
댓글 수: 0
Ameer Hamza
2020년 12월 8일
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
댓글 수: 0
Image Analyst
2020년 12월 8일
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
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!