If I have a matrix of 100 rows by 5 columns, how can I make it a 1 row x 500 column matrix, where each row (1x5) is placed one after the other to make a 1x500 matrix?

3 次查看(过去 30 天)
[r,c] = size(data);%(100 rows by 5 columns)
datanew = zeros(1,500)%
for i = 1:r
startcol = (1+(i-1)*5);
endcol = (5*i);
datanew(1,data(1,startcol:endcol)); %I get an error "Subscript indices must either be real positive integers or logicals." But data(1,startcol:endcol) does contain the correct 1x5 data, therefore, uncertain why the error.
end

采纳的回答

James Tursa
James Tursa 2016-11-2
datanew = reshape(data',1,[]);

更多回答(3 个)

Mischa Kim
Mischa Kim 2016-11-2
Use the reshape command.

Nick Counts
Nick Counts 2016-11-2
编辑:Nick Counts 2016-11-2
You can use reshape:
A = randi(10,100,5)
B = reshape(A,1,500)
  • A will be a 100x5 matrix
  • B will be a 500x1 matrix
As to your particular error, I am not certain. Your code doesn't work as posted because data isn't defined. So I can't say what's going on. If you want to post some additional code, we can take a look at what's going on and help you find the issue.
  1 个评论
Nick Counts
Nick Counts 2016-11-2
If you were trying to do this inside a for-loop, you can use horizcat or vertcat. You could also use indexing tricks, but your calculation of startcol and endcol seems to be broken. Easier to go row by row.
data = randi(10,100,5)
newData = []
for i = 1:length(data)
newData = vertcat(newData, data(i,:)');
end
I believe James's reshape is what you're really looking for

请先登录,再进行评论。


Eric
Eric 2016-11-3
I appreciate all the suggestions.

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by