Pre-alocating an array and locating last empty cells
显示 更早的评论
Hi
I am currently doing a project Euler problem for Pythagorean triplets. I have decided to use matrix transformation to produce my results. It takes a single set of triplets and transforms them with three matrix to produce three new sets triplets, each of these in turn can then be passed through the matrix to produce further triplets, creating a tree of results.
Where I am stuck is how do I store each set of triplets in my pre-allocated array. I need to step incrementally through the array to pick up my new triplets to be transformed and produce three answers that need storing. Do I use two counters, to me this feels messy and inelegant. Is there another way I need to be looking at storing the answers in the array. Advice always gratefully received, thanks.
As requested some code to show what I would like to achieve.
function PyTout = PyTrip(PyTin)
% A Pythagorean triplet is a set of three natural numbers, a b c, for which,
% a2 + b2 = c2
%
% For example, 32 + 42 = 9 + 16 = 25 = 52.
%
% There exists exactly one Pythagorean triplet for which a + b + c = 1000.
% Find the product abc.
%matrix for triplets, row one parent triplet, row 2,3,4 new triplet
PyMx = zeros(4,1000);
%load PyMx with parent (0) and first Py triplet (3 4 5)
PyMx(1:4,1) = [0 3 4 5 ];
%three transformation matrix for new Py Triplets
TripTrans1 = [-1 2 2; -2 1 2; -2 2 3];
TripTrans2 = [1 2 2; 2 1 2; 2 2 3];
TripTrans3 = [1 -2 2; 2 1 2; 2 -2 3];
for i = 1:(length(PyMx)/3)
TempMx1 = PyMx(2:4,i);
%first transformation,
TempMx2 = TripTrans1 * TempMx1;
%load into matrix, 2nd column
PyMx(1:4,2) = [i TempMx2(1:1) TempMx2(2:2) TempMx2(3:3)];
TempMx3 = TripTrans2 * TempMx1;
%load into matrix, 3rd column
PyMx(1:4,3) = [i TempMx3(1:1) TempMx3(2:2) TempMx3(3:3)];
TempMx4 = TripTrans3 * TempMx1;
%load into matrix, 4th column
PyMx(1:4,4) = [i TempMx4(1:1) TempMx4(2:2) TempMx4(3:3)];
%now need to perform again, stepping to second column but three ans need
%to go into 5th, 6th, 7th columns
end
I could implement a second counter to increment each time I perform a TMx1, TMx,2 TMx3 calculation. But I am asking is there a more efficient way to do this and load the data into the matrix. to me I seem to be typing out a lot of long hand, is there a better, more effitiant or preffered way I should do this. I am not just trying to find the ans to the problem (I could look at wiki page of Py triplets and get excel to sum them and give me an ans) I am also trying to improve my programing and how I think about it. Thanks for your time.
2 个评论
Fangjun Jiang
2011-11-10
Provide your example code or pseudo-code might be helpful.
bym
2011-11-10
Indeed, some sample code would help. I don't see where the problem requires you to store the triplets
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!