Info
This question is closed. Reopen it to edit or answer.
Help converting an array to a matrix with 5 columns
1 view (last 30 days)
Show older comments
I have been working on a script for a while and am towards the tail end of it. I need to convert the array that goes from 1:number to a matrix that has 5 columns. I can't seem to figure out how to do it. If anyone can help me please help out. Here is my code:
% clear
clear
% clc
clc
name=input('Enter name:','s');
% Ask user to input name
number=input('Enter a whole number between 1 and 100:');
% Ask user for a whole number between 1 and 100
while number<1 || number>100 || round(number)~=number
% a while function that performs actions under if number doesn't meet
% specifications
display('Not a valid number please try again');
number=input('Enter a whole number between 1 and 100:');
end
% End while loop
array=[1:number]
% Create array from 1 to input number
entryposition=0
% Set entry position to 0 for start of loop below
arraylength=length(array)
% Create arraylength variable to help find every multiple of 3
for i = 1:arraylength
% For loop to make each multiple of 3 negative in final array
entryposition=(entryposition+1);
% Cause array to go up by 1 until it meets the input
if mod(array(entryposition),3)==0;
% Check for multiples of 3
array(entryposition)=array(entryposition)*-1;
% Make 3's negative
end
end
disp(array)
disp('Thank you!')
disp(name)
% Thank user for running code
1 Comment
James Tursa
on 30 Jan 2020
Edited: James Tursa
on 30 Jan 2020
You could use reshape( ), possibly with a transpose. But what if the number of elements in the array is not a multiple of 5?
Also, you don't need the entryposition variable ... just use the index i directly.
Finally, you might look at the result of array(3:3:end) and that could give you a hint on how to vectorize this code instead of using a loop.
Answers (1)
Vinai Datta Thatiparthi
on 3 Feb 2020
Hey James,
From the description you've provided, this could be a possible solution -
(To echo @James' notes, if the variable number is not a multiple of 5, I've used zero-padding)
array = 1:number;
numRows = ceil(number/5);
arrayNew = [array zeros(1, numRows*5 - number)];
reshape(arrayNew, [numRows, 5])
Also, note that the output value of reshape will follow the column-major order.
Hope this helps!
0 Comments
This question is closed.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!