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 views (last 30 days)
Show older comments
[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
0 Comments
Accepted Answer
James Tursa
on 2 Nov 2016
datanew = reshape(data',1,[]);
1 Comment
Nick Counts
on 2 Nov 2016
Good catch with the transpose - re-reading Jean's code, it looks like he's trying to go row-by-row, rather than column-wise.
More Answers (3)
Nick Counts
on 2 Nov 2016
Edited: Nick Counts
on 2 Nov 2016
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 Comment
Nick Counts
on 2 Nov 2016
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
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!