Reshaping (M,N)-matrix to (M,1)-matrix

Hello everyone,
I have a matrix, for example:
A = [1, 2, 3;
4, 5, 6;
7, 8, 9]
and now I want to create a matrix:
A = [123;
456;
789]
Does anybody know how I can do this efficiently?
(I need to do this 62.000 times for my matrix)

 採用された回答

Andrei Bobrov
Andrei Bobrov 2013 年 11 月 8 日
編集済み: Andrei Bobrov 2013 年 11 月 8 日

0 投票

z = floor(log10(A)+1);
z(isinf(z)) = 1;
ex = fliplr(cumsum([zeros(size(A,1),1), fliplr(z(:,2:end))],2));
out = sum(A.*10.^ex,2);
eg:
> A =[14 10 3 16
12 0 10 18
3 11 14 7
9 13 0 20];
> z = floor(log10(A)+1);
> z(isinf(z)) = 1;
> ex = fliplr(cumsum([zeros(size(A,1),1), fliplr(z(:,2:end))],2));
> out = sum(A.*10.^ex,2)
out =
1410316
1201018
311147
913020

3 件のコメント

Jonathan
Jonathan 2013 年 11 月 8 日
Thanks! Works like a charm and fast as well!
Jonathan
Jonathan 2013 年 11 月 8 日
Only one small problem with this:
It adds zeroes to the end of my numbers and I would like that not to happen since my numbers are timestamps. Do you know how I can stop Matlab from adding those extra zeroes?
Thanks in advance!
Andrei Bobrov
Andrei Bobrov 2013 年 11 月 8 日
I corrected.

サインインしてコメントする。

その他の回答 (2 件)

Jos (10584)
Jos (10584) 2013 年 11 月 8 日

1 投票

Another trick using strings:
A = [1 2 3 ; 10 11 12 ; 90 0 99]
B = str2num(sprintf([repmat('%d',1,size(A,2)) ' '],A.')).'

2 件のコメント

Andrei Bobrov
Andrei Bobrov 2013 年 11 月 8 日
+1
Jos (10584)
Jos (10584) 2013 年 11 月 8 日
Note that you can play around with the "%d". For instance, you can use "%02d" so that a single digit number will be have a leading zero.

サインインしてコメントする。

Simon
Simon 2013 年 11 月 8 日
編集済み: Simon 2013 年 11 月 8 日

0 投票

Hi!
So your resulting matrix is a vector. right?
Try this
mat10 = ones(size(A, 1), 1) * 10.^((size(A, 2)-1):-1:0);
sum(A .* mat10, 2)
This is applicable for matrices of any size.
In string form
str2num(char(regexprep(cellstr(num2str(A)), ' ', '')))

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by