For loop to create a matrix array
显示 更早的评论
I have a data X say
X= 1:100 (integer 1 to 100)
I want to write a for loop that will create matrix of w=10x5 (10rows, 5 columns) where by column 1 will be the first 10 elements of X (1 to 10), column 2 (11 to 20) and so on and then stop at column 5 (41 to 50) before creating another matrix say w2 (ie starting the iteration again).
I don't want to use reshape function as it won't fit into the real data I am working on.
4 个评论
Matt J
2022-2-6
I don't want to use reshape function as it won't fit into the real data I am working on.
No, the reshape() function is exactly the thing to use for what you're talking about. What do you mean "it won't fit"?
Cutie
2022-2-6
Image Analyst
2022-2-6
编辑:Image Analyst
2022-2-6
For 90, what are the sizes of the two matrices?
- 9-by-5? (in which case, my answer below works)
- Or one matrix of 10-by-5 and the second one of 10-by-4?
Cutie
2022-2-7
采纳的回答
更多回答(1 个)
Try this
N = 100; % or 90 or some other multiple of 10
X= 1 : N; % (integer 1 to 100)
x1 = reshape(X(1:N/2)', N/10, [])
x2 = reshape(X(N/2+1:end), N/10, [])
If you don't want to use reshape for some weird reason, you can do it with a for loop but it will be more complicated.
X = 1 : 100;
x3 = zeros(10, 5);
x4 = zeros(10, 5);
k = 1;
for col = 1 : 5
for row = 1 : 10
x3(row, col) = X(k);
x4(row, col) = X(k + 50);
k = k + 1;
end
end
x3
x4
3 个评论
Cutie
2022-2-7
Navita
2023-2-21
Output not showing
Image Analyst
2023-2-21
@Navita as you can see above there is an output. I ran it in the editor with the green run triangle and there is definitely an output. Just look at my Answer and you can see it.
If you don't have any output then you must have copied my code and changed it somehow.
If you have any more questions, then attach your data and code to read it in with the paperclip icon after you read this:
类别
在 帮助中心 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!