简体   繁体   中英

Merge matrix in for loop matlab

i have a matrix c[38,39] , and want to merge it to a new one lets say f[1,1482] . So first i pre-allocate the f and then in a for loop i tried to merge it, but it keeps saying that i exceeded the matrix dimensions.I know that there is the cat function but i get the same results, maybe the reshape function will help? Any advice appretiated, thanks in advance.

f=[];       %// pre-allocating the mew matrix
for k=1:1482    %// 1482=38*39
f(:,k)=[c(:,1);c(:,k)]; %// merging 
end

It exceeds matrix dimensions because the second dimension of c is 39 and your loop is referencing values up to 1482.

Reshape may help if you are looking at different matrix sizes but if you are just wanting to convert from a matrix to a vector then just using the (:) notation works.

c=rand(38,39);
f=c(:)';

ps. pre-allocating f only really helps if you specify the final matrix size. Here all you have done is declared an empty matrix which then expands on each loop iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM