Keeping the indexed matrix the same shape as its index

Why does f(index) get transposed exclusively when f contains three variables?
f=[1 2 3 4];
n=numel(f)-1;
p=(1:n)';
q=(1:n-1);
index=(floor((p+n.*(q-1)-1)./(n-1))+1)
index = 3×2
1 2 1 3 2 3
f(index)
ans = 3×2
1 2 1 3 2 3
f=[1 2 3 ];
n=numel(f)-1;
p=(1:n)';
q=(1:n-1);
index=(floor((p+n.*(q-1)-1)./(n-1))+1)
index = 2×1
1 2
f(index)
ans = 1×2
1 2

Answers (1)

Why does f(index) get transposed exclusively when f contains three variables?
It is not exclusive to f having three elements. It is related to the fact that f and index are both vectors, in which case the orientation of f decides the shape,
f=[1,2,3,4,5,6];
f([1,2,5,6])
ans = 1×4
1 2 5 6
f([1,2,5,6].')
ans = 1×4
1 2 5 6
f([1,2;5 6])
ans = 2×2
1 2 5 6

1 Comment

In other words, if you want the result to consistently have the shape of index, you must do,
reshape(f(index),size(index))

Sign in to comment.

Categories

Tags

Asked:

A T
on 1 Nov 2020

Commented:

on 2 Nov 2020

Community Treasure Hunt

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

Start Hunting!