Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

Help converting an array to a matrix with 5 columns

조회 수: 1 (최근 30일)
John Furman
John Furman 2020년 1월 30일
마감: MATLAB Answer Bot 2021년 8월 20일
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
James Tursa
James Tursa 2020년 1월 30일
편집: James Tursa 2020년 1월 30일
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.

답변 (1개)

Vinai Datta Thatiparthi
Vinai Datta Thatiparthi 2020년 2월 3일
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!

이 질문은 마감되었습니다.

제품


릴리스

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by