MATLAB: For loops and vectorisation

fprintf for loops vectorisationhomework

a) Write a script which uses for loops to calculate the resistance of the copper wire at the five lengths. Display the results in two columns, one for the length and one for the resistance
b) Write additional script which uses vectorisation to calculate the resistance of the copper wire at the five lengths

Best Answer

Well, if you went straight to the vectorisation solution it is a bit silly to also require a for loop solution, but I guess if those are the questions you have to answer you have to do the reverse of what is usually done and instead of operating on your vector of values all at once just put in a loop from 1 upto the length of the vector (array) and basically do the same maths, but with array indexing for the single element being worked on in the current loop.
As a silly example that you should be able to derive from for your example:
a = [1 2 3 4 5];
b = a + 6;
is obviously trivial vectorisation. However if you wanted to be inefficient you could equally do it as:
a = [1 2 3 4 5];
b = zeros( size(A) );
for i = 1:5
b(i) = a(i) + 6;
end
Your question doesn't seem to say you have to use fprintf, it is a function useful for writing formatted data to file. sprintf would be the equivalent to just create a string for display purposes.
Related Question