create new matrix with special structure
2 次查看(过去 30 天)
显示 更早的评论
I have a Matrix named p. the sixe of it is m*n (m=6, n=4)
I want to create new matrix based on matrix p with aid of following rule
of course my real Matrix has a large size (500*500*6) and this question is just an example.
I write some thing but it must repeat in columns with so called rule and also I must save it in special structure
and my simple code:
for j=0:2:m-1
newmatrix=[p(1+j,1) p(2+j,1)]
0 个评论
采纳的回答
更多回答(2 个)
Yona
2015-1-11
编辑:Yona
2015-1-11
The simple way:
for j=0:2:m-1
for i=1:n
newmatrix(1+j,2*i-1:2*i)=p(j+[1 2],1);
end
end
Stephen23
2015-1-11
编辑:Stephen23
2015-1-11
Try this:
>> A = reshape(1:6*4,6,4); % define a fake data array of size 6x4
>> reshape([reshape(A(1:2:end-6),3,[]);reshape(A(2:2:end-6),3,[])],3,[])
ans =
1 2 7 8 13 14
3 4 9 10 15 16
5 6 11 12 17 18
This matches exactly with the sample output in your question.
Note that numel(output)/2 must be divisible by size(output,1) (in this example 18/2 = 9, which is divisible by 3 rows).
6 个评论
Stephen23
2015-1-11
The main way to reduce the number of loops in MATLAB is to use a feature of many operations and functions that can operate on complete arrays in one go without looping. This is known as vectorization . All basic arithmetic operations can operate on complete arrays, as can many, many functions. You will need to read the documentation carefully for a function to know if this is the case, and how to use it. Luckily the documentation always has good examples too!
Often vectorized code is (sometimes quite a lot) faster then loops, and it can also look a lot more like their equivalent mathematical operations than they would in other programming languages.
For example, instead of looping over elements in an array and performing some operation, you can use one of the several different indexing options to select all array elements that match some criteria, process these simultaneously and then return the results.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!